Rename _GlobalImport.cshtml files to _ViewImports.cshtml

- also rename files and directories with "GlobalImport" in name
 - nearly blind but avoid "ViewImportss" in new names
- public API change: `ViewHierarchyUtility.GetGlobalImportLocations()` -> `GetViewImportsLocations()`
 - primary source updates were comments, tests, and implementation details

nit:
- rename NestedGlobalImports.cs file to NestedViewImportsController.cs, matching class
This commit is contained in:
Doug Bunting 2015-05-21 10:08:53 -07:00
parent 78033fda1f
commit 8a701726b3
49 changed files with 157 additions and 157 deletions

View File

@ -14,7 +14,7 @@ using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Razor.Directives namespace Microsoft.AspNet.Mvc.Razor.Directives
{ {
/// <summary> /// <summary>
/// A utility type for supporting inheritance of directives into a page from applicable <c>_GlobalImport</c> pages. /// A utility type for supporting inheritance of directives into a page from applicable <c>_ViewImports</c> pages.
/// </summary> /// </summary>
public class ChunkInheritanceUtility public class ChunkInheritanceUtility
{ {
@ -25,7 +25,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
/// <summary> /// <summary>
/// Initializes a new instance of <see cref="ChunkInheritanceUtility"/>. /// Initializes a new instance of <see cref="ChunkInheritanceUtility"/>.
/// </summary> /// </summary>
/// <param name="razorHost">The <see cref="MvcRazorHost"/> used to parse <c>_GlobalImport</c> pages.</param> /// <param name="razorHost">The <see cref="MvcRazorHost"/> used to parse <c>_ViewImports</c> pages.</param>
/// <param name="codeTreeCache"><see cref="ICodeTreeCache"/> that caches <see cref="CodeTree"/> instances. /// <param name="codeTreeCache"><see cref="ICodeTreeCache"/> that caches <see cref="CodeTree"/> instances.
/// </param> /// </param>
/// <param name="defaultInheritedChunks">Sequence of <see cref="Chunk"/>s inherited by default.</param> /// <param name="defaultInheritedChunks">Sequence of <see cref="Chunk"/>s inherited by default.</param>
@ -40,27 +40,27 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
/// <summary> /// <summary>
/// Gets an ordered <see cref="IReadOnlyList{T}"/> of parsed <see cref="CodeTree"/> for each /// Gets an ordered <see cref="IReadOnlyList{T}"/> of parsed <see cref="CodeTree"/> for each
/// <c>_GlobalImport</c> that is applicable to the page located at <paramref name="pagePath"/>. The list is /// <c>_ViewImports</c> that is applicable to the page located at <paramref name="pagePath"/>. The list is
/// ordered so that the <see cref="CodeTree"/> for the <c>_GlobalImport</c> closest to the /// ordered so that the <see cref="CodeTree"/> for the <c>_ViewImports</c> closest to the
/// <paramref name="pagePath"/> in the file system appears first. /// <paramref name="pagePath"/> in the file system appears first.
/// </summary> /// </summary>
/// <param name="pagePath">The path of the page to locate inherited chunks for.</param> /// <param name="pagePath">The path of the page to locate inherited chunks for.</param>
/// <returns>A <see cref="IReadOnlyList{CodeTree}"/> of parsed <c>_GlobalImport</c> /// <returns>A <see cref="IReadOnlyList{CodeTree}"/> of parsed <c>_ViewImports</c>
/// <see cref="CodeTree"/>s.</returns> /// <see cref="CodeTree"/>s.</returns>
public virtual IReadOnlyList<CodeTree> GetInheritedCodeTrees([NotNull] string pagePath) public virtual IReadOnlyList<CodeTree> GetInheritedCodeTrees([NotNull] string pagePath)
{ {
var inheritedCodeTrees = new List<CodeTree>(); var inheritedCodeTrees = new List<CodeTree>();
var templateEngine = new RazorTemplateEngine(_razorHost); var templateEngine = new RazorTemplateEngine(_razorHost);
foreach (var globalImportPath in ViewHierarchyUtility.GetGlobalImportLocations(pagePath)) foreach (var viewImportsPath in ViewHierarchyUtility.GetViewImportsLocations(pagePath))
{ {
// globalImportPath contains the app-relative path of the _GlobalImport. // viewImportsPath contains the app-relative path of the _ViewImports.
// Since the parsing of a _GlobalImport would cause parent _GlobalImports to be parsed // Since the parsing of a _ViewImports would cause parent _ViewImports to be parsed
// we need to ensure the paths are app-relative to allow the GetGlobalFileLocations // we need to ensure the paths are app-relative to allow the GetGlobalFileLocations
// for the current _GlobalImport to succeed. // for the current _ViewImports to succeed.
var codeTree = _codeTreeCache.GetOrAdd(globalImportPath, var codeTree = _codeTreeCache.GetOrAdd(viewImportsPath,
fileInfo => ParseViewFile(templateEngine, fileInfo => ParseViewFile(templateEngine,
fileInfo, fileInfo,
globalImportPath)); viewImportsPath));
if (codeTree != null) if (codeTree != null)
{ {
@ -73,10 +73,10 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
/// <summary> /// <summary>
/// Merges <see cref="Chunk"/> inherited by default and <see cref="CodeTree"/> instances produced by parsing /// Merges <see cref="Chunk"/> inherited by default and <see cref="CodeTree"/> instances produced by parsing
/// <c>_GlobalImport</c> files into the specified <paramref name="codeTree"/>. /// <c>_ViewImports</c> files into the specified <paramref name="codeTree"/>.
/// </summary> /// </summary>
/// <param name="codeTree">The <see cref="CodeTree"/> to merge in to.</param> /// <param name="codeTree">The <see cref="CodeTree"/> to merge in to.</param>
/// <param name="inheritedCodeTrees"><see cref="IReadOnlyList{CodeTree}"/> inherited from <c>_GlobalImport</c> /// <param name="inheritedCodeTrees"><see cref="IReadOnlyList{CodeTree}"/> inherited from <c>_ViewImports</c>
/// files.</param> /// files.</param>
/// <param name="defaultModel">The list of chunks to merge.</param> /// <param name="defaultModel">The list of chunks to merge.</param>
public void MergeInheritedCodeTrees([NotNull] CodeTree codeTree, public void MergeInheritedCodeTrees([NotNull] CodeTree codeTree,
@ -99,7 +99,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
// In the second phase we invoke IChunkMerger.Merge for each chunk that has a mapped merger. // In the second phase we invoke IChunkMerger.Merge for each chunk that has a mapped merger.
// During this phase, the merger can either add to the CodeTree or ignore the chunk based on the merging // During this phase, the merger can either add to the CodeTree or ignore the chunk based on the merging
// rules. // rules.
// Read the chunks outside in - that is chunks from the _GlobalImport closest to the page get merged in first // Read the chunks outside in - that is chunks from the _ViewImports closest to the page get merged in first
// and the furthest one last. This allows the merger to ignore a directive like @model that was previously // and the furthest one last. This allows the merger to ignore a directive like @model that was previously
// seen. // seen.
var chunksToMerge = inheritedCodeTrees.SelectMany(tree => tree.Chunks) var chunksToMerge = inheritedCodeTrees.SelectMany(tree => tree.Chunks)
@ -126,18 +126,18 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
private static CodeTree ParseViewFile(RazorTemplateEngine engine, private static CodeTree ParseViewFile(RazorTemplateEngine engine,
IFileInfo fileInfo, IFileInfo fileInfo,
string globalImportPath) string viewImportsPath)
{ {
using (var stream = fileInfo.CreateReadStream()) using (var stream = fileInfo.CreateReadStream())
{ {
using (var streamReader = new StreamReader(stream)) using (var streamReader = new StreamReader(stream))
{ {
var parseResults = engine.ParseTemplate(streamReader, globalImportPath); var parseResults = engine.ParseTemplate(streamReader, viewImportsPath);
var className = ParserHelpers.SanitizeClassName(fileInfo.Name); var className = ParserHelpers.SanitizeClassName(fileInfo.Name);
var language = engine.Host.CodeLanguage; var language = engine.Host.CodeLanguage;
var codeGenerator = language.CreateCodeGenerator(className, var codeGenerator = language.CreateCodeGenerator(className,
engine.Host.DefaultNamespace, engine.Host.DefaultNamespace,
globalImportPath, viewImportsPath,
engine.Host); engine.Host);
codeGenerator.Visit(parseResults); codeGenerator.Visit(parseResults);
@ -146,7 +146,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
foreach (var chunk in codeTree.Chunks) foreach (var chunk in codeTree.Chunks)
{ {
chunk.Start = new SourceLocation( chunk.Start = new SourceLocation(
globalImportPath, viewImportsPath,
chunk.Start.AbsoluteIndex, chunk.Start.AbsoluteIndex,
chunk.Start.LineIndex, chunk.Start.LineIndex,
chunk.Start.CharacterIndex); chunk.Start.CharacterIndex);

View File

@ -51,7 +51,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
var pagePath = cacheSetContext.Key; var pagePath = cacheSetContext.Key;
var getCodeTree = (Func<IFileInfo, CodeTree>)cacheSetContext.State; var getCodeTree = (Func<IFileInfo, CodeTree>)cacheSetContext.State;
// GetOrAdd is invoked for each _ViewStart that might potentially exist in the path. // GetOrAdd is invoked for each _ViewImports that might potentially exist in the path.
// We can avoid performing file system lookups for files that do not exist by caching // We can avoid performing file system lookups for files that do not exist by caching
// negative results and adding a Watch for that file. // negative results and adding a Watch for that file.
cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(pagePath)); cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(pagePath));

View File

@ -17,11 +17,11 @@ namespace Microsoft.AspNet.Mvc.Razor
{ {
/// <summary> /// <summary>
/// A subtype of <see cref="RazorParser"/> that <see cref="MvcRazorHost"/> uses to support inheritance of tag /// A subtype of <see cref="RazorParser"/> that <see cref="MvcRazorHost"/> uses to support inheritance of tag
/// helpers from <c>_GlobalImport</c> files. /// helpers from <c>_ViewImports</c> files.
/// </summary> /// </summary>
public class MvcRazorParser : RazorParser public class MvcRazorParser : RazorParser
{ {
private readonly IEnumerable<TagHelperDirectiveDescriptor> _globalImportDirectiveDescriptors; private readonly IEnumerable<TagHelperDirectiveDescriptor> _viewImportsDirectiveDescriptors;
private readonly string _modelExpressionTypeName; private readonly string _modelExpressionTypeName;
/// <summary> /// <summary>
@ -29,7 +29,7 @@ namespace Microsoft.AspNet.Mvc.Razor
/// </summary> /// </summary>
/// <param name="parser">The <see cref="RazorParser"/> to copy properties from.</param> /// <param name="parser">The <see cref="RazorParser"/> to copy properties from.</param>
/// <param name="inheritedCodeTrees">The <see cref="IReadOnlyList{CodeTree}"/>s that are inherited /// <param name="inheritedCodeTrees">The <see cref="IReadOnlyList{CodeTree}"/>s that are inherited
/// from parsed pages from _GlobalImport files.</param> /// from parsed pages from _ViewImports files.</param>
/// <param name="defaultInheritedChunks">The <see cref="IReadOnlyList{Chunk}"/> inherited by /// <param name="defaultInheritedChunks">The <see cref="IReadOnlyList{Chunk}"/> inherited by
/// default by all Razor pages in the application.</param> /// default by all Razor pages in the application.</param>
public MvcRazorParser( public MvcRazorParser(
@ -40,7 +40,7 @@ namespace Microsoft.AspNet.Mvc.Razor
: base(parser) : base(parser)
{ {
// Construct tag helper descriptors from @addTagHelper, @removeTagHelper and @tagHelperPrefix chunks // Construct tag helper descriptors from @addTagHelper, @removeTagHelper and @tagHelperPrefix chunks
_globalImportDirectiveDescriptors = GetTagHelperDirectiveDescriptors( _viewImportsDirectiveDescriptors = GetTagHelperDirectiveDescriptors(
inheritedCodeTrees, inheritedCodeTrees,
defaultInheritedChunks); defaultInheritedChunks);
@ -52,9 +52,9 @@ namespace Microsoft.AspNet.Mvc.Razor
[NotNull] Block documentRoot, [NotNull] Block documentRoot,
[NotNull] ErrorSink errorSink) [NotNull] ErrorSink errorSink)
{ {
var visitor = new GlobalImportTagHelperDirectiveSpanVisitor( var visitor = new ViewImportsTagHelperDirectiveSpanVisitor(
TagHelperDescriptorResolver, TagHelperDescriptorResolver,
_globalImportDirectiveDescriptors, _viewImportsDirectiveDescriptors,
errorSink); errorSink);
var descriptors = visitor.GetDescriptors(documentRoot); var descriptors = visitor.GetDescriptors(documentRoot);
@ -86,13 +86,13 @@ namespace Microsoft.AspNet.Mvc.Razor
var descriptors = new List<TagHelperDirectiveDescriptor>(); var descriptors = new List<TagHelperDirectiveDescriptor>();
// For tag helpers, the @removeTagHelper only applies tag helpers that were added prior to it. // For tag helpers, the @removeTagHelper only applies tag helpers that were added prior to it.
// Consequently we must visit tag helpers outside-in - furthest _GlobalImport first and nearest one last. // Consequently we must visit tag helpers outside-in - furthest _ViewImports first and nearest one last.
// This is different from the behavior of chunk merging where we visit the nearest one first and ignore // This is different from the behavior of chunk merging where we visit the nearest one first and ignore
// chunks that were previously visited. // chunks that were previously visited.
var chunksFromGlobalImports = inheritedCodeTrees var chunksFromViewImports = inheritedCodeTrees
.Reverse() .Reverse()
.SelectMany(tree => tree.Chunks); .SelectMany(tree => tree.Chunks);
var chunksInOrder = defaultInheritedChunks.Concat(chunksFromGlobalImports); var chunksInOrder = defaultInheritedChunks.Concat(chunksFromViewImports);
foreach (var chunk in chunksInOrder) foreach (var chunk in chunksInOrder)
{ {
// All TagHelperDirectiveDescriptors created here have undefined source locations because the source // All TagHelperDirectiveDescriptors created here have undefined source locations because the source
@ -138,24 +138,24 @@ namespace Microsoft.AspNet.Mvc.Razor
return descriptors; return descriptors;
} }
private class GlobalImportTagHelperDirectiveSpanVisitor : TagHelperDirectiveSpanVisitor private class ViewImportsTagHelperDirectiveSpanVisitor : TagHelperDirectiveSpanVisitor
{ {
private readonly IEnumerable<TagHelperDirectiveDescriptor> _globalImportDirectiveDescriptors; private readonly IEnumerable<TagHelperDirectiveDescriptor> _viewImportsDirectiveDescriptors;
public GlobalImportTagHelperDirectiveSpanVisitor( public ViewImportsTagHelperDirectiveSpanVisitor(
ITagHelperDescriptorResolver descriptorResolver, ITagHelperDescriptorResolver descriptorResolver,
IEnumerable<TagHelperDirectiveDescriptor> globalImportDirectiveDescriptors, IEnumerable<TagHelperDirectiveDescriptor> viewImportsDirectiveDescriptors,
ErrorSink errorSink) ErrorSink errorSink)
: base(descriptorResolver, errorSink) : base(descriptorResolver, errorSink)
{ {
_globalImportDirectiveDescriptors = globalImportDirectiveDescriptors; _viewImportsDirectiveDescriptors = viewImportsDirectiveDescriptors;
} }
protected override TagHelperDescriptorResolutionContext GetTagHelperDescriptorResolutionContext( protected override TagHelperDescriptorResolutionContext GetTagHelperDescriptorResolutionContext(
IEnumerable<TagHelperDirectiveDescriptor> descriptors, IEnumerable<TagHelperDirectiveDescriptor> descriptors,
ErrorSink errorSink) ErrorSink errorSink)
{ {
var directivesToImport = MergeDirectiveDescriptors(descriptors, _globalImportDirectiveDescriptors); var directivesToImport = MergeDirectiveDescriptors(descriptors, _viewImportsDirectiveDescriptors);
return base.GetTagHelperDescriptorResolutionContext(directivesToImport, errorSink); return base.GetTagHelperDescriptorResolutionContext(directivesToImport, errorSink);
} }

View File

@ -9,12 +9,12 @@ using System.Linq;
namespace Microsoft.AspNet.Mvc.Razor namespace Microsoft.AspNet.Mvc.Razor
{ {
/// <summary> /// <summary>
/// Contains methods to locate <c>_ViewStart.cshtml</c> and <c>_GlobalImport.cshtml</c> /// Contains methods to locate <c>_ViewStart.cshtml</c> and <c>_ViewImports.cshtml</c>
/// </summary> /// </summary>
public static class ViewHierarchyUtility public static class ViewHierarchyUtility
{ {
private const string ViewStartFileName = "_ViewStart.cshtml"; private const string ViewStartFileName = "_ViewStart.cshtml";
private const string GlobalImportFileName = "_GlobalImport.cshtml"; private const string ViewImportsFileName = "_ViewImports.cshtml";
/// <summary> /// <summary>
/// Gets the view start locations that are applicable to the specified path. /// Gets the view start locations that are applicable to the specified path.
@ -34,21 +34,21 @@ namespace Microsoft.AspNet.Mvc.Razor
} }
/// <summary> /// <summary>
/// Gets the locations for <c>_GlobalImport</c>s that are applicable to the specified path. /// Gets the locations for <c>_ViewImports</c>s that are applicable to the specified path.
/// </summary> /// </summary>
/// <param name="applicationRelativePath">The application relative path of the file to locate /// <param name="applicationRelativePath">The application relative path of the file to locate
/// <c>_GlobalImport</c>s for.</param> /// <c>_ViewImports</c>s for.</param>
/// <returns>A sequence of paths that represent potential <c>_GlobalImport</c> locations.</returns> /// <returns>A sequence of paths that represent potential <c>_ViewImports</c> locations.</returns>
/// <remarks> /// <remarks>
/// This method returns paths starting from the directory of <paramref name="applicationRelativePath"/> and /// This method returns paths starting from the directory of <paramref name="applicationRelativePath"/> and
/// moves upwards until it hits the application root. /// moves upwards until it hits the application root.
/// e.g. /// e.g.
/// /Views/Home/View.cshtml -> [ /Views/Home/_GlobalImport.cshtml, /Views/_GlobalImport.cshtml, /// /Views/Home/View.cshtml -> [ /Views/Home/_ViewImports.cshtml, /Views/_ViewImports.cshtml,
/// /_GlobalImport.cshtml ] /// /_ViewImports.cshtml ]
/// </remarks> /// </remarks>
public static IEnumerable<string> GetGlobalImportLocations(string applicationRelativePath) public static IEnumerable<string> GetViewImportsLocations(string applicationRelativePath)
{ {
return GetHierarchicalPath(applicationRelativePath, GlobalImportFileName); return GetHierarchicalPath(applicationRelativePath, ViewImportsFileName);
} }
private static IEnumerable<string> GetHierarchicalPath(string relativePath, string fileName) private static IEnumerable<string> GetHierarchicalPath(string relativePath, string fileName)

View File

@ -64,16 +64,16 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
} }
} }
// Set up _GlobalImports // Set up _ViewImports
foreach (var entry in cacheEntries) foreach (var entry in cacheEntries)
{ {
var globalFileLocations = ViewHierarchyUtility.GetGlobalImportLocations(entry.RelativePath); var globalFileLocations = ViewHierarchyUtility.GetViewImportsLocations(entry.RelativePath);
foreach (var location in globalFileLocations) foreach (var location in globalFileLocations)
{ {
var globalFileEntry = _cache.Get<CompilerCacheEntry>(location); var globalFileEntry = _cache.Get<CompilerCacheEntry>(location);
if (globalFileEntry != null) if (globalFileEntry != null)
{ {
// Add the the composite _GlobalImport entry as a dependency. // Add the composite _ViewImports entry as a dependency.
entry.AssociatedGlobalFileEntry = globalFileEntry; entry.AssociatedGlobalFileEntry = globalFileEntry;
break; break;
} }
@ -113,7 +113,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
else if (cacheEntry.IsPreCompiled && !cacheEntry.IsValidatedPreCompiled) else if (cacheEntry.IsPreCompiled && !cacheEntry.IsValidatedPreCompiled)
{ {
// For precompiled views, the first time the entry is read, we need to ensure that no changes were made // For precompiled views, the first time the entry is read, we need to ensure that no changes were made
// either to the file associated with this entry, or any _GlobalImport associated with it between the time // either to the file associated with this entry, or any _ViewImports associated with it between the time
// the View was precompiled and the time EnsureInitialized was called. For later iterations, we can // the View was precompiled and the time EnsureInitialized was called. For later iterations, we can
// rely on expiration triggers ensuring the validity of the entry. // rely on expiration triggers ensuring the validity of the entry.
@ -132,7 +132,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
if (AssociatedGlobalFilesChanged(cacheEntry, compile)) if (AssociatedGlobalFilesChanged(cacheEntry, compile))
{ {
// Recompile if _GlobalImports have changed since the entry was created. // Recompile if _ViewImports have changed since the entry was created.
return OnCacheMiss(relativeFileInfo, normalizedPath, compile); return OnCacheMiss(relativeFileInfo, normalizedPath, compile);
} }
@ -199,8 +199,8 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
var entry = (CompilerCacheEntry)cacheSetContext.State; var entry = (CompilerCacheEntry)cacheSetContext.State;
cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(entry.RelativePath)); cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(entry.RelativePath));
var globalImportPaths = ViewHierarchyUtility.GetGlobalImportLocations(cacheSetContext.Key); var viewImportsPaths = ViewHierarchyUtility.GetViewImportsLocations(cacheSetContext.Key);
foreach (var location in globalImportPaths) foreach (var location in viewImportsPaths)
{ {
cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(location)); cacheSetContext.AddExpirationTrigger(_fileProvider.Watch(location));
} }
@ -215,24 +215,24 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
return entry.AssociatedGlobalFileEntry != globalFileEntry; return entry.AssociatedGlobalFileEntry != globalFileEntry;
} }
// Returns the entry for the nearest _GlobalImport that the file inherits directives from. Since _GlobalImport // Returns the entry for the nearest _ViewImports that the file inherits directives from. Since _ViewImports
// entries are affected by other _GlobalImport entries that are in the path hierarchy, the returned value // entries are affected by other _ViewImports entries that are in the path hierarchy, the returned value
// represents the composite result of performing a cache check on individual _GlobalImport entries. // represents the composite result of performing a cache check on individual _ViewImports entries.
private CompilerCacheEntry GetCompositeGlobalFileEntry(string relativePath, private CompilerCacheEntry GetCompositeGlobalFileEntry(string relativePath,
Func<RelativeFileInfo, CompilationResult> compile) Func<RelativeFileInfo, CompilationResult> compile)
{ {
var globalImportLocations = ViewHierarchyUtility.GetGlobalImportLocations(relativePath); var viewImportsLocations = ViewHierarchyUtility.GetViewImportsLocations(relativePath);
foreach (var globalImport in globalImportLocations) foreach (var viewImports in viewImportsLocations)
{ {
var getOrAddResult = GetOrAddCore(globalImport, compile); var getOrAddResult = GetOrAddCore(viewImports, compile);
if (getOrAddResult != null) if (getOrAddResult != null)
{ {
// This is the nearest _GlobalImport that exists on disk. // This is the nearest _ViewImports that exists on disk.
return getOrAddResult.CompilerCacheEntry; return getOrAddResult.CompilerCacheEntry;
} }
} }
// No _GlobalImports discovered. // No _ViewImports discovered.
return null; return null;
} }

View File

@ -80,7 +80,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
public bool IsPreCompiled { get; } public bool IsPreCompiled { get; }
/// <summary> /// <summary>
/// Gets or sets the <see cref="CompilerCacheEntry"/> for the nearest _GlobalImport that the compiled type /// Gets or sets the <see cref="CompilerCacheEntry"/> for the nearest _ViewImports that the compiled type
/// depends on. /// depends on.
/// </summary> /// </summary>
public CompilerCacheEntry AssociatedGlobalFileEntry { get; set; } public CompilerCacheEntry AssociatedGlobalFileEntry { get; set; }

View File

@ -198,7 +198,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Precompilation
if (entry != null) if (entry != null)
{ {
cacheSetContext.AddExpirationTrigger(FileProvider.Watch(fileInfo.RelativePath)); cacheSetContext.AddExpirationTrigger(FileProvider.Watch(fileInfo.RelativePath));
foreach (var path in ViewHierarchyUtility.GetGlobalImportLocations(fileInfo.RelativePath)) foreach (var path in ViewHierarchyUtility.GetViewImportsLocations(fileInfo.RelativePath))
{ {
cacheSetContext.AddExpirationTrigger(FileProvider.Watch(path)); cacheSetContext.AddExpirationTrigger(FileProvider.Watch(path));
} }

View File

@ -24,7 +24,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var client = server.CreateClient(); var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsInjectAndUsingsFromGlobalImports"); var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsInjectAndUsingsFromViewImports");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());
@ -38,7 +38,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var client = server.CreateClient(); var client = server.CreateClient();
// Act // Act
var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromGlobalImports"); var body = await client.GetStringAsync("http://localhost/Directives/ViewInheritsBasePageFromViewImports");
// Assert // Assert
Assert.Equal(expected, body.Trim()); Assert.Equal(expected, body.Trim());

View File

@ -49,7 +49,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
} }
[Fact] [Fact]
public async Task CompilationFailuresFromGlobalImportAreListed() public async Task CompilationFailuresFromViewImportsAreListed()
{ {
// Arrange // Arrange
var expectedMessage = "The type or namespace name &#x27;NamespaceDoesNotExist&#x27; could not be found (" var expectedMessage = "The type or namespace name &#x27;NamespaceDoesNotExist&#x27; could not be found ("
@ -59,13 +59,13 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var expectedMediaType = MediaTypeHeaderValue.Parse("text/html"); var expectedMediaType = MediaTypeHeaderValue.Parse("text/html");
// Act // Act
var response = await client.GetAsync("http://localhost/ErrorFromGlobalImport"); var response = await client.GetAsync("http://localhost/ErrorFromViewImports");
// Assert // Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
Assert.Equal(expectedMediaType, response.Content.Headers.ContentType); Assert.Equal(expectedMediaType, response.Content.Headers.ContentType);
var content = await response.Content.ReadAsStringAsync(); var content = await response.Content.ReadAsStringAsync();
Assert.Contains(@"Views\ErrorFromGlobalImport\_GlobalImport.cshtml", content); Assert.Contains(@"Views\ErrorFromViewImports\_ViewImports.cshtml", content);
Assert.Contains(expectedMessage, content); Assert.Contains(expectedMessage, content);
} }
} }

View File

@ -43,7 +43,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var layoutContent = File.ReadAllText(Path.Combine(viewsDirectory, "Layout.cshtml")); var layoutContent = File.ReadAllText(Path.Combine(viewsDirectory, "Layout.cshtml"));
var indexContent = File.ReadAllText(Path.Combine(viewsDirectory, "Index.cshtml")); var indexContent = File.ReadAllText(Path.Combine(viewsDirectory, "Index.cshtml"));
var viewstartContent = File.ReadAllText(Path.Combine(viewsDirectory, "_ViewStart.cshtml")); var viewstartContent = File.ReadAllText(Path.Combine(viewsDirectory, "_ViewStart.cshtml"));
var globalContent = File.ReadAllText(Path.Combine(viewsDirectory, "_GlobalImport.cshtml")); var globalContent = File.ReadAllText(Path.Combine(viewsDirectory, "_ViewImports.cshtml"));
// We will render a view that writes the fully qualified name of the Assembly containing the type of // We will render a view that writes the fully qualified name of the Assembly containing the type of
// the view. If the view is precompiled, this assembly will be PrecompilationWebsite. // the view. If the view is precompiled, this assembly will be PrecompilationWebsite.
@ -85,8 +85,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(response2.Layout, response3.Layout); Assert.Equal(response2.Layout, response3.Layout);
// Act - 4 // Act - 4
// Touch the _GlobalImport file and verify it causes all files to recompile. // Touch the _ViewImports file and verify it causes all files to recompile.
await TouchFile(viewsDirectory, "_GlobalImport.cshtml"); await TouchFile(viewsDirectory, "_ViewImports.cshtml");
responseContent = await client.GetStringAsync("http://localhost/Home/Index"); responseContent = await client.GetStringAsync("http://localhost/Home/Index");
// Assert - 4 // Assert - 4
@ -108,8 +108,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.NotEqual(response4.Index, response5.Index); Assert.NotEqual(response4.Index, response5.Index);
// Act - 6 // Act - 6
// Touch the _GlobalImport file. This time, we'll verify the Non-precompiled -> Non-precompiled workflow. // Touch the _ViewImports file. This time, we'll verify the Non-precompiled -> Non-precompiled workflow.
await TouchFile(viewsDirectory, "_GlobalImport.cshtml"); await TouchFile(viewsDirectory, "_ViewImports.cshtml");
responseContent = await client.GetStringAsync("http://localhost/Home/Index"); responseContent = await client.GetStringAsync("http://localhost/Home/Index");
// Assert - 6 // Assert - 6
@ -120,8 +120,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.NotEqual(response5.Layout, response6.Layout); Assert.NotEqual(response5.Layout, response6.Layout);
// Act - 7 // Act - 7
// Add a new _GlobalImport file // Add a new _ViewImports file
var newGlobalImport = await TouchFile(Path.GetDirectoryName(viewsDirectory), "_GlobalImport.cshtml"); var newViewImports = await TouchFile(Path.GetDirectoryName(viewsDirectory), "_ViewImports.cshtml");
responseContent = await client.GetStringAsync("http://localhost/Home/Index"); responseContent = await client.GetStringAsync("http://localhost/Home/Index");
// Assert - 7 // Assert - 7
@ -132,8 +132,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.NotEqual(response6.Layout, response7.Layout); Assert.NotEqual(response6.Layout, response7.Layout);
// Act - 8 // Act - 8
// Remove new _GlobalImport file // Remove new _ViewImports file
File.Delete(newGlobalImport); File.Delete(newViewImports);
await Task.Delay(_cacheDelayInterval); await Task.Delay(_cacheDelayInterval);
responseContent = await client.GetStringAsync("http://localhost/Home/Index"); responseContent = await client.GetStringAsync("http://localhost/Home/Index");
@ -159,7 +159,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
File.WriteAllText(Path.Combine(viewsDirectory, "Layout.cshtml"), layoutContent.TrimEnd(' ')); File.WriteAllText(Path.Combine(viewsDirectory, "Layout.cshtml"), layoutContent.TrimEnd(' '));
File.WriteAllText(Path.Combine(viewsDirectory, "Index.cshtml"), indexContent.TrimEnd(' ')); File.WriteAllText(Path.Combine(viewsDirectory, "Index.cshtml"), indexContent.TrimEnd(' '));
File.WriteAllText(Path.Combine(viewsDirectory, "_ViewStart.cshtml"), viewstartContent.TrimEnd(' ')); File.WriteAllText(Path.Combine(viewsDirectory, "_ViewStart.cshtml"), viewstartContent.TrimEnd(' '));
File.WriteAllText(Path.Combine(viewsDirectory, "_GlobalImport.cshtml"), globalContent.TrimEnd(' ')); File.WriteAllText(Path.Combine(viewsDirectory, "_ViewImports.cshtml"), globalContent.TrimEnd(' '));
} }
} }
@ -205,8 +205,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
var viewsDirectory = Path.Combine(applicationEnvironment.ApplicationBasePath, var viewsDirectory = Path.Combine(applicationEnvironment.ApplicationBasePath,
"Views", "Views",
"GlobalImportDelete"); "ViewImportsDelete");
var globalPath = Path.Combine(viewsDirectory, "_GlobalImport.cshtml"); var globalPath = Path.Combine(viewsDirectory, "_ViewImports.cshtml");
var globalContent = File.ReadAllText(globalPath); var globalContent = File.ReadAllText(globalPath);
// Act - 1 // Act - 1

View File

@ -55,7 +55,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
Assert.Equal(expectedContent, responseContent); Assert.Equal(expectedContent, responseContent);
} }
public static TheoryData TagHelpersAreInheritedFromGlobalImportPagesData public static TheoryData TagHelpersAreInheritedFromViewImportsPagesData
{ {
get get
{ {
@ -63,7 +63,7 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
return new TheoryData<string, string> return new TheoryData<string, string>
{ {
{ {
"NestedGlobalImportTagHelper", "NestedViewImportsTagHelper",
string.Format( string.Format(
"<root>root-content</root>{0}{0}{0}<nested>nested-content</nested>", "<root>root-content</root>{0}{0}{0}<nested>nested-content</nested>",
Environment.NewLine) Environment.NewLine)
@ -109,8 +109,8 @@ namespace Microsoft.AspNet.Mvc.FunctionalTests
} }
[Theory] [Theory]
[MemberData(nameof(TagHelpersAreInheritedFromGlobalImportPagesData))] [MemberData(nameof(TagHelpersAreInheritedFromViewImportsPagesData))]
public async Task TagHelpersAreInheritedFromGlobalImportPages(string action, string expected) public async Task TagHelpersAreInheritedFromViewImportsPages(string action, string expected)
{ {
// Arrange // Arrange
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var server = TestHelper.CreateServer(_app, SiteName, _configureServices);

View File

@ -323,7 +323,7 @@ View With Layout
<page>Hello Controller-Person</page>"; <page>Hello Controller-Person</page>";
var server = TestHelper.CreateServer(_app, SiteName, _configureServices); var server = TestHelper.CreateServer(_app, SiteName, _configureServices);
var client = server.CreateClient(); var client = server.CreateClient();
var target = "http://localhost/NestedGlobalImports"; var target = "http://localhost/NestedViewImports";
// Act // Act
var body = await client.GetStringAsync(target); var body = await client.GetStringAsync(target);

View File

@ -13,10 +13,10 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
{ {
// Arrange // Arrange
var fileProvider = new TestFileProvider(); var fileProvider = new TestFileProvider();
fileProvider.AddFile(@"Views\accounts\_GlobalImport.cshtml", "@using AccountModels"); fileProvider.AddFile(@"Views\accounts\_ViewImports.cshtml", "@using AccountModels");
fileProvider.AddFile(@"Views\Shared\_GlobalImport.cshtml", "@inject SharedHelper Shared"); fileProvider.AddFile(@"Views\Shared\_ViewImports.cshtml", "@inject SharedHelper Shared");
fileProvider.AddFile(@"Views\home\_GlobalImport.cshtml", "@using MyNamespace"); fileProvider.AddFile(@"Views\home\_ViewImports.cshtml", "@using MyNamespace");
fileProvider.AddFile(@"Views\_GlobalImport.cshtml", fileProvider.AddFile(@"Views\_ViewImports.cshtml",
@"@inject MyHelper<TModel> Helper @"@inject MyHelper<TModel> Helper
@inherits MyBaseType @inherits MyBaseType
@ -41,67 +41,67 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
Assert.Collection(codeTrees, Assert.Collection(codeTrees,
codeTree => codeTree =>
{ {
var globalImportPath = @"Views\home\_GlobalImport.cshtml"; var viewImportsPath = @"Views\home\_ViewImports.cshtml";
Assert.Collection(codeTree.Chunks, Assert.Collection(codeTree.Chunks,
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
var usingChunk = Assert.IsType<UsingChunk>(chunk); var usingChunk = Assert.IsType<UsingChunk>(chunk);
Assert.Equal("MyNamespace", usingChunk.Namespace); Assert.Equal("MyNamespace", usingChunk.Namespace);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}); });
}, },
codeTree => codeTree =>
{ {
var globalImportPath = @"Views\_GlobalImport.cshtml"; var viewImportsPath = @"Views\_ViewImports.cshtml";
Assert.Collection(codeTree.Chunks, Assert.Collection(codeTree.Chunks,
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
var injectChunk = Assert.IsType<InjectChunk>(chunk); var injectChunk = Assert.IsType<InjectChunk>(chunk);
Assert.Equal("MyHelper<TModel>", injectChunk.TypeName); Assert.Equal("MyHelper<TModel>", injectChunk.TypeName);
Assert.Equal("Helper", injectChunk.MemberName); Assert.Equal("Helper", injectChunk.MemberName);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
var setBaseTypeChunk = Assert.IsType<SetBaseTypeChunk>(chunk); var setBaseTypeChunk = Assert.IsType<SetBaseTypeChunk>(chunk);
Assert.Equal("MyBaseType", setBaseTypeChunk.TypeName); Assert.Equal("MyBaseType", setBaseTypeChunk.TypeName);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
Assert.IsType<StatementChunk>(chunk); Assert.IsType<StatementChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}, },
chunk => chunk =>
{ {
Assert.IsType<LiteralChunk>(chunk); Assert.IsType<LiteralChunk>(chunk);
Assert.Equal(globalImportPath, chunk.Start.FilePath); Assert.Equal(viewImportsPath, chunk.Start.FilePath);
}); });
}); });
} }
@ -111,9 +111,9 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
{ {
// Arrange // Arrange
var fileProvider = new TestFileProvider(); var fileProvider = new TestFileProvider();
fileProvider.AddFile(@"_GlobalImport.cs", string.Empty); fileProvider.AddFile(@"_ViewImports.cs", string.Empty);
fileProvider.AddFile(@"Views\_Layout.cshtml", string.Empty); fileProvider.AddFile(@"Views\_Layout.cshtml", string.Empty);
fileProvider.AddFile(@"Views\home\_not-globalimport.cshtml", string.Empty); fileProvider.AddFile(@"Views\home\_not-viewimports.cshtml", string.Empty);
var cache = new DefaultCodeTreeCache(fileProvider); var cache = new DefaultCodeTreeCache(fileProvider);
var host = new MvcRazorHost(cache); var host = new MvcRazorHost(cache);
var defaultChunks = new Chunk[] var defaultChunks = new Chunk[]
@ -135,7 +135,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Directives
{ {
// Arrange // Arrange
var fileProvider = new TestFileProvider(); var fileProvider = new TestFileProvider();
fileProvider.AddFile(@"Views\_GlobalImport.cshtml", fileProvider.AddFile(@"Views\_ViewImports.cshtml",
"@inject DifferentHelper<TModel> Html"); "@inject DifferentHelper<TModel> Html");
var cache = new DefaultCodeTreeCache(fileProvider); var cache = new DefaultCodeTreeCache(fileProvider);
var host = new MvcRazorHost(cache); var host = new MvcRazorHost(cache);

View File

@ -17,7 +17,7 @@ namespace Microsoft.AspNet.Mvc.Razor
{ {
public class MvcRazorCodeParserTest public class MvcRazorCodeParserTest
{ {
public static TheoryData GlobalImportData public static TheoryData ViewImportsData
{ {
get get
{ {
@ -135,7 +135,7 @@ namespace Microsoft.AspNet.Mvc.Razor
} }
[Theory] [Theory]
[MemberData(nameof(GlobalImportData))] [MemberData(nameof(ViewImportsData))]
public void GetTagHelperDescriptors_ReturnsExpectedDirectiveDescriptors( public void GetTagHelperDescriptors_ReturnsExpectedDirectiveDescriptors(
CodeTree[] codeTrees, CodeTree[] codeTrees,
TagHelperDirectiveDescriptor[] expectedDirectiveDescriptors) TagHelperDirectiveDescriptor[] expectedDirectiveDescriptors)

View File

@ -23,10 +23,10 @@ namespace Microsoft.AspNet.Mvc.Razor
[Theory] [Theory]
[InlineData(null)] [InlineData(null)]
[InlineData("")] [InlineData("")]
public void GetGlobalImportLocations_ReturnsEmptySequenceIfViewPathIsEmpty(string viewPath) public void GetViewImportsLocations_ReturnsEmptySequenceIfViewPathIsEmpty(string viewPath)
{ {
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(viewPath); var result = ViewHierarchyUtility.GetViewImportsLocations(viewPath);
// Assert // Assert
Assert.Empty(result); Assert.Empty(result);
@ -57,18 +57,18 @@ namespace Microsoft.AspNet.Mvc.Razor
[InlineData("/Views/Home/MyView.cshtml")] [InlineData("/Views/Home/MyView.cshtml")]
[InlineData("~/Views/Home/MyView.cshtml")] [InlineData("~/Views/Home/MyView.cshtml")]
[InlineData("Views/Home/MyView.cshtml")] [InlineData("Views/Home/MyView.cshtml")]
public void GetGlobalImportLocations_ReturnsPotentialViewStartLocations_PathStartswithSlash(string inputPath) public void GetViewImportsLocations_ReturnsPotentialViewStartLocations_PathStartswithSlash(string inputPath)
{ {
// Arrange // Arrange
var expected = new[] var expected = new[]
{ {
@"Views\Home\_GlobalImport.cshtml", @"Views\Home\_ViewImports.cshtml",
@"Views\_GlobalImport.cshtml", @"Views\_ViewImports.cshtml",
@"_GlobalImport.cshtml" @"_ViewImports.cshtml"
}; };
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(inputPath); var result = ViewHierarchyUtility.GetViewImportsLocations(inputPath);
// Assert // Assert
Assert.Equal(expected, result); Assert.Equal(expected, result);
@ -98,38 +98,38 @@ namespace Microsoft.AspNet.Mvc.Razor
[InlineData("/Views/Home/_ViewStart.cshtml")] [InlineData("/Views/Home/_ViewStart.cshtml")]
[InlineData("~/Views/Home/_ViewStart.cshtml")] [InlineData("~/Views/Home/_ViewStart.cshtml")]
[InlineData("Views/Home/_ViewStart.cshtml")] [InlineData("Views/Home/_ViewStart.cshtml")]
public void GetGlobalImportLocations_WhenCurrentIsViewStart(string inputPath) public void GetViewImportsLocations_WhenCurrentIsViewStart(string inputPath)
{ {
// Arrange // Arrange
var expected = new[] var expected = new[]
{ {
@"Views\Home\_GlobalImport.cshtml", @"Views\Home\_ViewImports.cshtml",
@"Views\_GlobalImport.cshtml", @"Views\_ViewImports.cshtml",
@"_GlobalImport.cshtml" @"_ViewImports.cshtml"
}; };
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(inputPath); var result = ViewHierarchyUtility.GetViewImportsLocations(inputPath);
// Assert // Assert
Assert.Equal(expected, result); Assert.Equal(expected, result);
} }
[Theory] [Theory]
[InlineData("/Views/Home/_GlobalImport.cshtml")] [InlineData("/Views/Home/_ViewImports.cshtml")]
[InlineData("~/Views/Home/_GlobalImport.cshtml")] [InlineData("~/Views/Home/_ViewImports.cshtml")]
[InlineData("Views/Home/_GlobalImport.cshtml")] [InlineData("Views/Home/_ViewImports.cshtml")]
public void GetGlobalImportLocations_SkipsCurrentPath_IfCurrentIsGlobalImport(string inputPath) public void GetViewImportsLocations_SkipsCurrentPath_IfCurrentIsViewImports(string inputPath)
{ {
// Arrange // Arrange
var expected = new[] var expected = new[]
{ {
@"Views\_GlobalImport.cshtml", @"Views\_ViewImports.cshtml",
@"_GlobalImport.cshtml" @"_ViewImports.cshtml"
}; };
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(inputPath); var result = ViewHierarchyUtility.GetViewImportsLocations(inputPath);
// Assert // Assert
Assert.Equal(expected, result); Assert.Equal(expected, result);
@ -163,22 +163,22 @@ namespace Microsoft.AspNet.Mvc.Razor
[InlineData("Test.cshtml")] [InlineData("Test.cshtml")]
[InlineData("Global.cshtml")] [InlineData("Global.cshtml")]
[InlineData("_ViewStart.cshtml")] [InlineData("_ViewStart.cshtml")]
public void GetGlobalImportLocations_ReturnsPotentialGlobalLocations(string fileName) public void GetViewImportsLocations_ReturnsPotentialGlobalLocations(string fileName)
{ {
// Arrange // Arrange
var expected = new[] var expected = new[]
{ {
@"Areas\MyArea\Sub\Views\Admin\_GlobalImport.cshtml", @"Areas\MyArea\Sub\Views\Admin\_ViewImports.cshtml",
@"Areas\MyArea\Sub\Views\_GlobalImport.cshtml", @"Areas\MyArea\Sub\Views\_ViewImports.cshtml",
@"Areas\MyArea\Sub\_GlobalImport.cshtml", @"Areas\MyArea\Sub\_ViewImports.cshtml",
@"Areas\MyArea\_GlobalImport.cshtml", @"Areas\MyArea\_ViewImports.cshtml",
@"Areas\_GlobalImport.cshtml", @"Areas\_ViewImports.cshtml",
@"_GlobalImport.cshtml", @"_ViewImports.cshtml",
}; };
var viewPath = Path.Combine("Areas", "MyArea", "Sub", "Views", "Admin", fileName); var viewPath = Path.Combine("Areas", "MyArea", "Sub", "Views", "Admin", fileName);
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(viewPath); var result = ViewHierarchyUtility.GetViewImportsLocations(viewPath);
// Assert // Assert
Assert.Equal(expected, result); Assert.Equal(expected, result);
@ -234,13 +234,13 @@ namespace Microsoft.AspNet.Mvc.Razor
} }
[Fact] [Fact]
public void GetGlobalImportLocations_ReturnsEmptySequence_IfPathIsRooted() public void GetViewImportsLocations_ReturnsEmptySequence_IfPathIsRooted()
{ {
// Arrange // Arrange
var absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "Index.cshtml"); var absolutePath = Path.Combine(Directory.GetCurrentDirectory(), "Index.cshtml");
// Act // Act
var result = ViewHierarchyUtility.GetGlobalImportLocations(absolutePath); var result = ViewHierarchyUtility.GetViewImportsLocations(absolutePath);
// Assert // Assert
Assert.Empty(result); Assert.Empty(result);

View File

@ -267,14 +267,14 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
Content = globalContent, Content = globalContent,
LastModified = DateTime.UtcNow LastModified = DateTime.UtcNow
}; };
fileProvider.AddFile("_GlobalImport.cshtml", globalFileInfo); fileProvider.AddFile("_ViewImports.cshtml", globalFileInfo);
var globalRazorFileInfo = new RazorFileInfo var globalRazorFileInfo = new RazorFileInfo
{ {
Hash = Crc32.Calculate(GetMemoryStream(globalContent)).ToString(CultureInfo.InvariantCulture), Hash = Crc32.Calculate(GetMemoryStream(globalContent)).ToString(CultureInfo.InvariantCulture),
HashAlgorithmVersion = 1, HashAlgorithmVersion = 1,
LastModified = globalFileInfo.LastModified, LastModified = globalFileInfo.LastModified,
Length = globalFileInfo.Length, Length = globalFileInfo.Length,
RelativePath = "_GlobalImport.cshtml", RelativePath = "_ViewImports.cshtml",
FullTypeName = typeof(RuntimeCompileIdentical).FullName FullTypeName = typeof(RuntimeCompileIdentical).FullName
}; };
var precompiledViews = new ViewCollection(); var precompiledViews = new ViewCollection();
@ -349,7 +349,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
} }
[Fact] [Fact]
public void GetOrAdd_IgnoresCachedValueIfFileIsIdentical_ButGlobalImportWasAdedSinceTheCacheWasCreated() public void GetOrAdd_IgnoresCachedValueIfFileIsIdentical_ButViewImportsWasAdedSinceTheCacheWasCreated()
{ {
// Arrange // Arrange
var expectedType = typeof(RuntimeCompileDifferent); var expectedType = typeof(RuntimeCompileDifferent);
@ -378,7 +378,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
Assert.Equal(typeof(PreCompile), actual1.CompiledType); Assert.Equal(typeof(PreCompile), actual1.CompiledType);
// Act 2 // Act 2
var globalTrigger = fileProvider.GetTrigger("Views\\_GlobalImport.cshtml"); var globalTrigger = fileProvider.GetTrigger("Views\\_ViewImports.cshtml");
globalTrigger.IsExpired = true; globalTrigger.IsExpired = true;
var result2 = cache.GetOrAdd(testFile.PhysicalPath, var result2 = cache.GetOrAdd(testFile.PhysicalPath,
compile: _ => CompilationResult.Successful(expectedType)); compile: _ => CompilationResult.Successful(expectedType));
@ -411,7 +411,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
var globalFileInfo = new TestFileInfo var globalFileInfo = new TestFileInfo
{ {
PhysicalPath = "Views\\_GlobalImport.cshtml", PhysicalPath = "Views\\_ViewImports.cshtml",
Content = "viewstart-content", Content = "viewstart-content",
LastModified = lastModified LastModified = lastModified
}; };
@ -460,7 +460,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
var contentStream = GetMemoryStream(globalContent); var contentStream = GetMemoryStream(globalContent);
var lastModified = DateTime.UtcNow; var lastModified = DateTime.UtcNow;
int length = Encoding.UTF8.GetByteCount(globalContent); int length = Encoding.UTF8.GetByteCount(globalContent);
var path = "Views\\_GlobalImport.cshtml"; var path = "Views\\_ViewImports.cshtml";
var razorFileInfo = new RazorFileInfo var razorFileInfo = new RazorFileInfo
{ {

View File

@ -125,12 +125,12 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
{ {
// Arrange // Arrange
var viewPath = @"views/index.razor"; var viewPath = @"views/index.razor";
var globalImportPath = @"views/global.import.cshtml"; var viewImportsPath = @"views/global.import.cshtml";
var host = Mock.Of<IMvcRazorHost>(); var host = Mock.Of<IMvcRazorHost>();
var fileProvider = new TestFileProvider(); var fileProvider = new TestFileProvider();
var file = fileProvider.AddFile(viewPath, "View Content"); var file = fileProvider.AddFile(viewPath, "View Content");
fileProvider.AddFile(globalImportPath, "Global Import Content"); fileProvider.AddFile(viewImportsPath, "Global Import Content");
var relativeFileInfo = new RelativeFileInfo(file, viewPath); var relativeFileInfo = new RelativeFileInfo(file, viewPath);
var razorService = new RazorCompilationService( var razorService = new RazorCompilationService(
Mock.Of<ICompilationService>(), Mock.Of<ICompilationService>(),
@ -141,7 +141,7 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
new RazorError("message-1", new SourceLocation(1, 2, 17)), new RazorError("message-1", new SourceLocation(1, 2, 17)),
new RazorError("message-2", new SourceLocation(viewPath, 1, 4, 6), 7), new RazorError("message-2", new SourceLocation(viewPath, 1, 4, 6), 7),
new RazorError { Message = "message-3" }, new RazorError { Message = "message-3" },
new RazorError("message-4", new SourceLocation(globalImportPath, 1, 3, 8), 4), new RazorError("message-4", new SourceLocation(viewImportsPath, 1, 3, 8), 4),
}; };
// Act // Act
@ -185,13 +185,13 @@ namespace Microsoft.AspNet.Mvc.Razor.Compilation
}, },
failure => failure =>
{ {
Assert.Equal(globalImportPath, failure.SourceFilePath); Assert.Equal(viewImportsPath, failure.SourceFilePath);
Assert.Equal("Global Import Content", failure.SourceFileContent); Assert.Equal("Global Import Content", failure.SourceFileContent);
Assert.Collection(failure.Messages, Assert.Collection(failure.Messages,
message => message =>
{ {
Assert.Equal(errors[3].Message, message.Message); Assert.Equal(errors[3].Message, message.Message);
Assert.Equal(globalImportPath, message.SourceFilePath); Assert.Equal(viewImportsPath, message.SourceFilePath);
Assert.Equal(4, message.StartLine); Assert.Equal(4, message.StartLine);
Assert.Equal(8, message.StartColumn); Assert.Equal(8, message.StartColumn);
Assert.Equal(4, message.EndLine); Assert.Equal(4, message.EndLine);

View File

@ -19,10 +19,10 @@ namespace ErrorPageMiddlewareWebSite
return View(); return View();
} }
[HttpGet("/ErrorFromGlobalImport")] [HttpGet("/ErrorFromViewImports")]
public IActionResult GlobalImportError() public IActionResult ViewImportsError()
{ {
return View("~/Views/ErrorFromGlobalImport/Index"); return View("~/Views/ErrorFromViewImports/Index");
} }
} }
} }

View File

@ -19,7 +19,7 @@ namespace PrecompilationWebSite.Controllers
public IActionResult GlobalDeletedPriorToFirstRequest() public IActionResult GlobalDeletedPriorToFirstRequest()
{ {
return View("~/Views/GlobalImportDelete/Index"); return View("~/Views/ViewImportsDelete/Index");
} }
[HttpGet("/Test")] [HttpGet("/Test")]

View File

@ -7,14 +7,14 @@ namespace RazorWebSite
{ {
public class DirectivesController : Controller public class DirectivesController : Controller
{ {
public ViewResult ViewInheritsInjectAndUsingsFromGlobalImports() public ViewResult ViewInheritsInjectAndUsingsFromViewImports()
{ {
return View(new Person { Name = "Person1" }); return View(new Person { Name = "Person1" });
} }
public ViewResult ViewInheritsBasePageFromGlobalImports() public ViewResult ViewInheritsBasePageFromViewImports()
{ {
return View("/views/directives/scoped/ViewInheritsBasePageFromGlobalImports.cshtml", return View("/views/directives/scoped/ViewInheritsBasePageFromViewImports.cshtml",
new Person { Name = "Person2" }); new Person { Name = "Person2" });
} }
} }

View File

@ -5,7 +5,7 @@ using Microsoft.AspNet.Mvc;
namespace RazorWebSite.Controllers namespace RazorWebSite.Controllers
{ {
public class NestedGlobalImportsController : Controller public class NestedViewImportsController : Controller
{ {
public ViewResult Index() public ViewResult Index()
{ {
@ -14,7 +14,7 @@ namespace RazorWebSite.Controllers
Name = "Controller-Person" Name = "Controller-Person"
}; };
return View("~/Views/NestedGlobalImports/Nested/Index.cshtml", model); return View("~/Views/NestedViewImports/Nested/Index.cshtml", model);
} }
} }
} }

View File

@ -30,7 +30,7 @@ namespace TagHelpersWebSite.Controllers
return View(); return View();
} }
public ViewResult NestedGlobalImportTagHelper() public ViewResult NestedViewImportsTagHelper()
{ {
return View(); return View();
} }

View File

@ -7,7 +7,7 @@ using Microsoft.AspNet.Razor.TagHelpers;
namespace TagHelpersWebSite.TagHelpers namespace TagHelpersWebSite.TagHelpers
{ {
[TargetElement("nested")] [TargetElement("nested")]
public class NestedGlobalImportTagHelper : TagHelper public class NestedViewImportsTagHelper : TagHelper
{ {
public override void Process(TagHelperContext context, TagHelperOutput output) public override void Process(TagHelperContext context, TagHelperOutput output)
{ {

View File

@ -1 +0,0 @@
@addTagHelper "TagHelpersWebSite.TagHelpers.NestedGlobalImportTagHelper, TagHelpersWebSite"

View File

@ -0,0 +1 @@
@addTagHelper "TagHelpersWebSite.TagHelpers.NestedViewImportsTagHelper, TagHelpersWebSite"

View File

@ -1,2 +1,2 @@
@removeTagHelper "TagHelpersWebSite.TagHelpers.RootViewStartTagHelper, TagHelpersWebSite" @removeTagHelper "TagHelpersWebSite.TagHelpers.RootViewStartTagHelper, TagHelpersWebSite"
@addTagHelper "TagHelpersWebSite.TagHelpers.NestedGlobalImportTagHelper, TagHelpersWebSite" @addTagHelper "TagHelpersWebSite.TagHelpers.NestedViewImportsTagHelper, TagHelpersWebSite"

View File

@ -1,5 +1,5 @@
@{ @{
Layout = "~/Views/Shared/_LayoutWithRootTagHelper.cshtml"; Layout = "~/Views/Shared/_LayoutWithRootTagHelper.cshtml";
} }
@addTagHelper "TagHelpersWebSite.TagHelpers.NestedGlobalImportTagHelper, TagHelpersWebSite" @addTagHelper "TagHelpersWebSite.TagHelpers.NestedViewImportsTagHelper, TagHelpersWebSite"
<nested>some-content</nested> <nested>some-content</nested>