// Copyright (c) .NET Foundation. 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.Linq;
using Microsoft.AspNet.Mvc.Razor.Host;
using Microsoft.AspNet.Razor.Chunks;
using Microsoft.Framework.Internal;
namespace Microsoft.AspNet.Mvc.Razor.Directives
{
///
/// Contains helper methods for dealing with Chunks
///
public static class ChunkHelper
{
private const string TModelToken = "";
///
/// Attempts to cast the passed in to type and throws if the
/// cast fails.
///
/// The type to cast to.
/// The chunk to cast.
/// The cast to .
/// is not an instance of
/// .
public static TChunk EnsureChunk([NotNull] Chunk chunk)
where TChunk : Chunk
{
var chunkOfT = chunk as TChunk;
if (chunkOfT == null)
{
var message = Resources.FormatArgumentMustBeOfType(typeof(TChunk).FullName);
throw new ArgumentException(message, nameof(chunk));
}
return chunkOfT;
}
///
/// Returns the used to determine the model name for the page generated
/// using the specified
///
/// The to scan for s in.
/// The last in the if found, null otherwise.
///
public static ModelChunk GetModelChunk([NotNull] ChunkTree chunkTree)
{
// If there's more than 1 model chunk there will be a Razor error BUT we want intellisense to show up on
// the current model chunk that the user is typing.
return chunkTree.Chunks
.OfType()
.LastOrDefault();
}
///
/// Returns the type name of the Model specified via a in the
/// if specified or the default model type.
///
/// The to scan for s in.
/// The name of the default model.
/// The model type name for the generated page.
public static string GetModelTypeName(
[NotNull] ChunkTree chunkTree,
[NotNull] string defaultModelName)
{
var modelChunk = GetModelChunk(chunkTree);
return modelChunk != null ? modelChunk.ModelType : defaultModelName;
}
///
/// Returns a string with the <TModel> token replaced with the value specified in
/// .
///
/// The string to replace the token in.
/// The model name to replace with.
/// A string with the token replaced.
public static string ReplaceTModel([NotNull] string value,
[NotNull] string modelName)
{
return value.Replace(TModelToken, modelName);
}
}
}