// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System.IO;
namespace System.Web.WebPages
{
///
/// The can take any suffix and determine if there is a corresponding
/// file that exists given a path and request by transforming the path to contain the suffix.
/// Add a new DefaultDisplayMode to the Modes collection to handle a new suffix or inherit from
/// DefaultDisplayMode to provide custom logic to transform paths with a suffix.
///
public class DefaultDisplayMode : IDisplayMode
{
private readonly string _suffix;
public DefaultDisplayMode()
: this(DisplayModeProvider.DefaultDisplayModeId)
{
}
public DefaultDisplayMode(string suffix)
{
_suffix = suffix ?? String.Empty;
}
///
/// When set, the will only be available to return Display Info for a request
/// if the ContextCondition evaluates to true.
///
public Func ContextCondition { get; set; }
public virtual string DisplayModeId
{
get { return _suffix; }
}
public bool CanHandleContext(HttpContextBase httpContext)
{
return ContextCondition == null || ContextCondition(httpContext);
}
///
/// Returns DisplayInfo with the transformed path if it exists.
///
public virtual DisplayInfo GetDisplayInfo(HttpContextBase httpContext, string virtualPath, Func virtualPathExists)
{
string transformedFilename = TransformPath(virtualPath, _suffix);
if (transformedFilename != null && virtualPathExists(transformedFilename))
{
return new DisplayInfo(transformedFilename, this);
}
return null;
}
///
/// Transforms paths according to the following rules:
/// \some\path.blah\file.txt.zip -> \some\path.blah\file.txt.suffix.zip
/// \some\path.blah\file -> \some\path.blah\file.suffix
///
protected virtual string TransformPath(string virtualPath, string suffix)
{
if (String.IsNullOrEmpty(suffix))
{
return virtualPath;
}
string extension = Path.GetExtension(virtualPath);
return Path.ChangeExtension(virtualPath, suffix + extension);
}
}
}