Removed Old Razor Stuff

This commit is contained in:
Elijah
2011-01-20 21:55:51 -10:00
parent 8ada4a4e1e
commit 17efba1242
8 changed files with 0 additions and 624 deletions

View File

@@ -1,33 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System.CodeDom.Compiler;
using System.Web.Razor;
using Microsoft.CSharp;
/// <summary>
/// Provides a razor provider that supports the C# syntax.
/// </summary>
public class CSharpRazorProvider : IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
public RazorCodeLanguage CreateLanguageService()
{
return new CSharpRazorCodeLanguage();
}
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
public CodeDomProvider CreateCodeDomProvider()
{
return new CSharpCodeProvider();
}
#endregion
}
}

View File

@@ -1,26 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Web.Razor;
/// <summary>
/// Defines a provider used to create associated compiler types.
/// </summary>
public interface IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
RazorCodeLanguage CreateLanguageService();
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
CodeDomProvider CreateCodeDomProvider();
#endregion
}
}

View File

@@ -1,58 +0,0 @@
using System.Dynamic;
namespace umbraco.MacroEngines.Razor
{
/// <summary>
/// A razor template.
/// </summary>
public interface ITemplate
{
#region Properties
/// <summary>
/// Gets the parsed result of the template.
/// </summary>
string Result { get; }
#endregion
#region Methods
/// <summary>
/// Clears the template.
/// </summary>
void Clear();
/// <summary>
/// Executes the template.
/// </summary>
void Execute();
/// <summary>
/// Writes the specified object to the template.
/// </summary>
/// <param name="object"></param>
void Write(object @object);
/// <summary>
/// Writes a literal to the template.
/// </summary>
/// <param name="literal"></param>
void WriteLiteral(string literal);
#endregion
}
/// <summary>
/// A razor template with a model.
/// </summary>
/// <typeparam name="TModel">The model type</typeparam>
public interface ITemplate<TModel> : ITemplate
{
#region Properties
/// <summary>
/// Gets or sets the model.
/// </summary>
TModel Model { get; set; }
#endregion
}
public interface ITemplateDynamic : ITemplate {
dynamic Model { get; set; }
}
}

View File

@@ -1,87 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System;
using System.Collections.Generic;
/// <summary>
/// Process razor templates.
/// </summary>
public static class Razor
{
#region Fields
private static RazorCompiler Compiler;
private static readonly IDictionary<string, ITemplate> Templates;
#endregion
#region Constructor
/// <summary>
/// Statically initialises the <see cref="Razor"/> type.
/// </summary>
static Razor()
{
Compiler = new RazorCompiler(new CSharpRazorProvider());
Templates = new Dictionary<string, ITemplate>();
}
#endregion
#region Methods
/// <summary>
/// Gets an <see cref="ITemplate"/> for the specified template.
/// </summary>
/// <param name="template">The template to parse.</param>
/// <param name="modelType">The model to use in the template.</param>
/// <param name="name">[Optional] The name of the template.</param>
/// <returns></returns>
private static ITemplate GetTemplate(string template, Type modelType, string name = null)
{
if (!string.IsNullOrEmpty(name))
{
if (Templates.ContainsKey(name))
return Templates[name];
}
var instance = Compiler.CreateTemplate(template, modelType);
if (!string.IsNullOrEmpty(name))
{
if (!Templates.ContainsKey(name))
Templates.Add(name, instance);
}
return instance;
}
/// <summary>
/// Parses the specified template using the specified model.
/// </summary>
/// <typeparam name="T">The model type.</typeparam>
/// <param name="template">The template to parse.</param>
/// <param name="model">The model to use in the template.</param>
/// <param name="name">[Optional] A name for the template used for caching.</param>
/// <returns>The parsed template.</returns>
public static string Parse<T>(string template, T model, string name = null)
{
var instance = GetTemplate(template, typeof(T), name);
if (instance is ITemplate<T>)
((ITemplate<T>)instance).Model = model;
else if (instance is ITemplateDynamic)
((ITemplateDynamic)instance).Model = model;
instance.Execute();
return instance.Result;
}
/// <summary>
/// Sets the razor provider used for compiling templates.
/// </summary>
/// <param name="provider">The razor provider.</param>
public static void SetRazorProvider(IRazorProvider provider)
{
if (provider == null)
throw new ArgumentNullException("provider");
Compiler = new RazorCompiler(provider);
}
#endregion
}
}

View File

@@ -1,204 +0,0 @@
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace umbraco.MacroEngines.Razor
{
using System;
using System.CodeDom.Compiler;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Razor;
using System.Web.Razor.Parser;
using System.Runtime.CompilerServices;
/// <summary>
/// Compiles razor templates.
/// </summary>
internal class RazorCompiler
{
#region Fields
private readonly IRazorProvider provider;
private Type templateBaseType;
#endregion
#region Constructor
/// <summary>
/// Initialises a new instance of <see cref="RazorCompiler"/>.
/// </summary>
/// <param name="provider">The provider used to compile templates.</param>
public RazorCompiler(IRazorProvider provider)
{
if (provider == null)
throw new ArgumentNullException("provider");
this.provider = provider;
}
#endregion
#region Methods
/// <summary>
/// Compiles the template.
/// </summary>
/// <param name="className">The class name of the dynamic type.</param>
/// <param name="template">The template to compile.</param>
/// <param name="modelType">[Optional] The mode type.</param>
private CompilerResults Compile(string className, string template, Type modelType = null)
{
var languageService = provider.CreateLanguageService();
var codeDom = provider.CreateCodeDomProvider();
var host = new RazorEngineHost(languageService);
var generator = languageService.CreateCodeGenerator(className, "Razor.Dynamic", null, host);
var parser = new RazorParser(languageService.CreateCodeParser(), new HtmlMarkupParser());
// Umbraco hack for use with DynamicNode
bool anonymousType = modelType.FullName == "umbraco.MacroEngines.DynamicNode" || (modelType.IsClass && modelType.IsSealed && modelType.BaseType == typeof(object) && modelType.Name.StartsWith("<>") && modelType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), true) != null);
//There's no simple way of determining if an object is an anonymous type - this seems like a problem
Type baseType = (modelType == null)
? typeof(TemplateBase)
: (anonymousType
? typeof(TemplateBaseDynamic)
: typeof(TemplateBase<>).MakeGenericType(modelType));
templateBaseType = baseType;
generator.GeneratedClass.BaseTypes.Add(baseType);
using (var reader = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(template))))
{
parser.Parse(reader, generator);
}
var statement = new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "Clear");
generator.GeneratedExecuteMethod.Statements.Insert(0, new CodeExpressionStatement(statement));
var builder = new StringBuilder();
using (var writer = new StringWriter(builder))
{
codeDom.GenerateCodeFromCompileUnit(generator.GeneratedCode, writer, new CodeGeneratorOptions());
}
var parameters = new CompilerParameters();
AddReferences(parameters);
parameters.GenerateInMemory = true;
parameters.IncludeDebugInformation = false;
parameters.GenerateExecutable = false;
parameters.CompilerOptions = "/target:library /optimize";
var result = codeDom.CompileAssemblyFromSource(parameters, new[] { builder.ToString() });
return result;
}
/// <summary>
/// Creates a <see cref="ITemplate" /> from the specified template string.
/// </summary>
/// <param name="template">The template to compile.</param>
/// <param name="modelType">[Optional] The model type.</param>
/// <returns>An instance of <see cref="ITemplate"/>.</returns>
public ITemplate CreateTemplate(string template, Type modelType = null)
{
string className = Regex.Replace(Guid.NewGuid().ToString("N"), @"[^A-Za-z]*", "");
var result = Compile(className, template, modelType);
if (result.Errors != null && result.Errors.Count > 0)
throw new TemplateException(result.Errors);
ITemplate instance = (ITemplate)result.CompiledAssembly.CreateInstance("Razor.Dynamic." + className);
return instance;
}
#endregion
/// <summary>
/// Adds any required references to the compiler parameters.
/// </summary>
/// <param name="parameters">The compiler parameters.</param>
private void AddReferences(CompilerParameters parameters)
{
var list = new List<string>();
IEnumerable<string> coreRefs = GetCoreReferences();
foreach (string location in coreRefs)
{
list.Add(location.ToLowerInvariant());
}
IEnumerable<string> baseRefs = GetBaseTypeReferencedAssemblies();
foreach (string location in baseRefs)
{
list.Add(location.ToLowerInvariant());
}
foreach (string location in list)
System.Diagnostics.Debug.Print(location);
IEnumerable<string> distinctList = list.Distinct(new AssemblyVersionComparer());
parameters.ReferencedAssemblies.AddRange(distinctList.ToArray());
}
/// <summary>
/// Gets the locations of assemblies referenced by a custom base template type.
/// </summary>
/// <returns>An enumerable of reference assembly locations.</returns>
private IEnumerable<string> GetBaseTypeReferencedAssemblies()
{
if (templateBaseType == null)
return new string[0];
return templateBaseType.Assembly
.GetReferencedAssemblies()
.Select(n => Assembly.ReflectionOnlyLoad(n.FullName).Location);
}
/// <summary>
/// Gets the locations of all core referenced assemblies.
/// </summary>
/// <returns>An enumerable of reference assembly locations.</returns>
private static IEnumerable<string> GetCoreReferences()
{
var refs = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic).Select(a => a.Location);
return refs.Concat(typeof(RazorCompiler)
.Assembly
.GetReferencedAssemblies().Select(n => Assembly.ReflectionOnlyLoad(n.FullName).Location));
}
}
public class AssemblyVersionComparer : IEqualityComparer<string>
{
bool IEqualityComparer<string>.Equals(string x, string y)
{
x = findAssemblyName(x);
y = findAssemblyName(y);
return (x.Contains(y) || y.Contains(x));
}
int IEqualityComparer<string>.GetHashCode(string obj)
{
// 1) find the assembly name without version number and path (xxx.yyy.dll)
obj = findAssemblyName(obj);
// 2) send det som hashcode
if (Object.ReferenceEquals(obj, null))
return 0;
return obj.GetHashCode();
}
private string findAssemblyName(string fullAssemblyPath)
{
Regex r = new Regex(@"\\([^\\]*.dll)");
Match m = r.Match(fullAssemblyPath);
if (m.Groups.Count > 0)
{
fullAssemblyPath = m.Groups[0].Value;
}
return fullAssemblyPath;
}
}
}

View File

@@ -1,146 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System.Text;
using System.IO;
using System.Globalization;
using System.Dynamic;
using System;
using System.Runtime.CompilerServices;
/// <summary>
/// Provides a base implementation of a template.
/// </summary>
public abstract class TemplateBase : ITemplate
{
#region Fields
private TextWriter builder = new StringWriter(CultureInfo.InvariantCulture);
#endregion
#region Properties
/// <summary>
/// Gets the parsed result of the template.
/// </summary>
public string Result { get { return builder.ToString(); } }
#endregion
#region Methods
/// <summary>
/// Clears the template.
/// </summary>
public void Clear()
{
builder = new StringWriter(CultureInfo.InvariantCulture);
}
/// <summary>
/// Executes the template.
/// </summary>
public virtual void Execute() { }
/// <summary>
/// Writes the specified object to the template.
/// </summary>
/// <param name="object"></param>
public void Write(object @object)
{
if (@object == null)
return;
builder.Write(@object);
}
/// <summary>
/// Writes a literal to the template.
/// </summary>
/// <param name="literal"></param>
public void WriteLiteral(string literal)
{
if (literal == null)
return;
builder.Write(literal);
}
#endregion
}
/// <summary>
/// Provides a base implementation of a template.
/// </summary>
/// <typeparam name="TModel">The model type.</typeparam>
public abstract class TemplateBase<TModel> : TemplateBase, ITemplate<TModel>
{
#region Properties
public TModel Model { get; set; }
/// <summary>
/// Gets or sets the model.
/// </summary>
#endregion
}
/// <summary>
/// Inherits form TemplateBase and provides an anonymous type implementation
/// </summary>
public abstract class TemplateBaseDynamic : TemplateBase, ITemplateDynamic
{
dynamic model;
/// <summary>
/// Gets or sets an anonymous type model
/// </summary>
public dynamic Model
{
get
{
return model;
}
set
{
model = new RazorDynamicObject() { Model = value };
}
}
/// <summary>
/// Dynamic object that we'll utilize to return anonymous type parameters
/// </summary>
class RazorDynamicObject : DynamicObject
{
internal object Model { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
bool isDynamicNode = false;
object tempResult = null;
try
{
if (Model.GetType().FullName == "umbraco.MacroEngines.DynamicNode")
{
isDynamicNode = ((DynamicObject)Model).TryGetMember(binder, out tempResult);
}
}
catch
{
result = "";
}
if (!isDynamicNode)
{
tempResult = Model.GetType().InvokeMember(binder.Name,
System.Reflection.BindingFlags.GetProperty |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic,
null,
Model,
null);
}
result = tempResult;
return true;
}
}
}
}

View File

@@ -1,37 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
/// <summary>
/// Defines an exception that occurs during compilation of a template.
/// </summary>
public class TemplateException : Exception
{
#region Constructors
/// <summary>
/// Initialises a new instance of <see cref="TemplateException"/>
/// </summary>
/// <param name="errors">The collection of compilation errors.</param>
internal TemplateException(CompilerErrorCollection errors) : base("Unable to compile template.")
{
var list = new List<CompilerError>();
foreach (CompilerError error in errors)
{
list.Add(error);
}
Errors = new ReadOnlyCollection<CompilerError>(list);
}
#endregion
#region Properties
/// <summary>
/// Gets the collection of compiler errors.
/// </summary>
public ReadOnlyCollection<CompilerError> Errors { get; private set; }
#endregion
}
}

View File

@@ -1,33 +0,0 @@
namespace umbraco.MacroEngines.Razor
{
using System.CodeDom.Compiler;
using System.Web.Razor;
using Microsoft.VisualBasic;
/// <summary>
/// Provides a razor provider that supports the VB syntax.
/// </summary>
public class VBRazorProvider : IRazorProvider
{
#region Methods
/// <summary>
/// Creates a code language service.
/// </summary>
/// <returns>Creates a language service.</returns>
public RazorCodeLanguage CreateLanguageService()
{
return new VBRazorCodeLanguage();
}
/// <summary>
/// Creates a <see cref="CodeDomProvider"/>.
/// </summary>
/// <returns>The a code dom provider.</returns>
public CodeDomProvider CreateCodeDomProvider()
{
return new VBCodeProvider();
}
#endregion
}
}