Skip to content

loading all local assemblies when building razor view #85

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace Simple.Web.Razor.Tests.ExternalDummyAssembly
{
public static class DummyHelper
{
public static string DummyString { get { return "Hello world!"; } }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Simple.Web.Razor.Tests.ExternalDummyAssembly")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Simple.Web.Razor.Tests.ExternalDummyAssembly")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("75324d66-0f05-4548-88f6-7a445914c9ca")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{93A1F038-AF12-4BEA-8EFB-13007A01EF50}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Simple.Web.Razor.Tests.ExternalDummyAssembly</RootNamespace>
<AssemblyName>Simple.Web.Razor.Tests.ExternalDummyAssembly</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="DummyHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
37 changes: 37 additions & 0 deletions src/Simple.Web.Razor.Tests/RazorTypeBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,43 @@ public void GetsComplexModelTypeFromRazorMarkup()
Assert.Equal(1, genericArguments.Length);
Assert.Equal(typeof(IEnumerable<TestModel>), genericArguments[0]);
}


[Fact]
public void GetTypeFromViewWithExternalUsing()
{
const string templateText = @"
@using Simple.Web.Razor.Tests.ExternalDummyAssembly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p>@DummyHelper.DummyString</p>
</body>
</html>
";
var type = RazorTypeBuilderHelpers.CreateTypeFromText(templateText);
Assert.NotNull(type);
}

[Fact]
public void GetTypeFromViewWithExternalFullyQualifiedReference()
{
const string templateText = @"
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<p>@Simple.Web.Razor.Tests.ExternalDummyAssembly.DummyHelper.DummyString</p>
</body>
</html>";
var type = RazorTypeBuilderHelpers.CreateTypeFromText(templateText);
Assert.NotNull(type);
}
}

public class TestHandler
Expand Down
4 changes: 4 additions & 0 deletions src/Simple.Web.Razor.Tests/Simple.Web.Razor.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@
<Compile Include="TypeNameTranslatorTests.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Simple.Web.Razor.Tests.ExternalDummyAssembly\Simple.Web.Razor.Tests.ExternalDummyAssembly.csproj">
<Project>{93a1f038-af12-4bea-8efb-13007a01ef50}</Project>
<Name>Simple.Web.Razor.Tests.ExternalDummyAssembly</Name>
</ProjectReference>
<ProjectReference Include="..\Simple.Web.Razor\Simple.Web.Razor.csproj">
<Project>{A226D857-22FD-4C10-8596-EB7821C59255}</Project>
<Name>Simple.Web.Razor</Name>
Expand Down
67 changes: 3 additions & 64 deletions src/Simple.Web.Razor/RazorTypeBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,14 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web.Razor;

using Microsoft.CSharp;

using Simple.Web.Razor.Engine;

internal class RazorTypeBuilder
{
private static readonly Dictionary<string, Action<string, RazorTypeBuilderContext>>
DirectiveHandlers =
new Dictionary<string, Action<string, RazorTypeBuilderContext>>()
{
{"@handler", ReadHandler},
{"@model", ReadModel}
};

private static readonly IDictionary<String, String> CompilerProperties =
new Dictionary<String, String> { { "CompilerVersion", "v4.0" } };

Expand All @@ -31,57 +24,14 @@ public Type CreateType(StreamReader reader)

private static Type CreateTypeImpl(StreamReader reader)
{
var context = CreateContext(reader);
var context = new RazorTypeBuilderContext();

var engine = CreateRazorTemplateEngine();
var razorResult = engine.GenerateCode(reader, context.ClassName, engine.Host.DefaultNamespace, null);
var viewType = CompileView(razorResult, context.GetCompilerParameters());

return viewType;
}
private static void ReadModel(string line, RazorTypeBuilderContext context)
{
var type = TypeHelper.FindTypeFromRazorLine(line, "@model");
context.SetModel(type);
}

private static void ReadHandler(string line, RazorTypeBuilderContext context)
{
var type = TypeHelper.FindTypeFromRazorLine(line, "@handler");
context.SetHandler(type);
}

private static List<string> GetLines(StreamReader reader)
{
var lines = new List<string>();
string line;
while ((line = reader.ReadLine()) != null)
{
lines.Add(line);
}
reader.BaseStream.Position = 0;
return lines;
}

private static RazorTypeBuilderContext CreateContext(StreamReader reader)
{
var context = new RazorTypeBuilderContext();
var lines = GetLines(reader);
PreProcess(lines, context);
return context;
}

private static void PreProcess(List<string> lines, RazorTypeBuilderContext context)
{
lines.ForEach(y =>
{
var directive = y.Split(' ')[0];
if (DirectiveHandlers.Keys.Contains(directive))
{
DirectiveHandlers[directive](y, context);
}
});
}

private static RazorTemplateEngine CreateRazorTemplateEngine()
{
Expand Down Expand Up @@ -119,15 +69,4 @@ private static Type CompileView(GeneratorResults razorResult, CompilerParameters
return type;
}
}

internal static class TypeHelper
{
private static readonly TypeResolver TypeResolver = new TypeResolver();

public static Type FindTypeFromRazorLine(string line, string directive)
{
string typeName = line.Replace(directive, string.Empty).Trim();
return TypeHelper.TypeResolver.FindType(typeName);
}
}
}
68 changes: 34 additions & 34 deletions src/Simple.Web.Razor/RazorTypeBuilderContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,9 @@ internal class RazorTypeBuilderContext
private static readonly string[] ExcludedReferencesOnMono =
new[] { "System", "System.Core", "Microsoft.CSharp", "mscorlib" };

private static readonly Func<Assembly, bool> IsValidReference = an =>
((Type.GetType("Mono.Runtime") == null) || !ExcludedReferencesOnMono.Any(an.Location.Contains));

private Type _model;
private Type _handler;
private CompilerParameters _compilerParameters;
private string _className;
private List<Assembly> _declarationAssemblies;
private readonly CompilerParameters _compilerParameters;
private readonly string _className;
private List<Assembly> _defaultAssemblies;

public RazorTypeBuilderContext()
{
Expand All @@ -34,45 +29,50 @@ public RazorTypeBuilderContext()
OutputAssembly = Path.Combine(Path.GetTempPath(), string.Format("{0}.dll", _className)),
MainClass = _className
};

_declarationAssemblies = new List<Assembly>();
}

public string ClassName {get { return _className; }}

public void SetModel(Type model)
private IEnumerable<Assembly> DefaultAssemblies
{
_model = model;
AddAssemblyForType(_model);
get
{
if (_defaultAssemblies == null)
{
var folderAssemblies = ScanFolderForAssemblies();
_defaultAssemblies = SimpleRazorConfiguration.NamespaceImports.Where(ni => ni.Value != null)
.Select(ni => ni.Value)
.Concat(folderAssemblies)
.Where(IsValidReference)
.Where(an => !an.IsDynamic)
.GroupBy(an => an.FullName)
.Select(an => an.First())
.ToList();
}
return _defaultAssemblies;
}
}

public void SetHandler(Type handler)
private static IEnumerable<Assembly> ScanFolderForAssemblies()
{
_handler = handler;
AddAssemblyForType(_handler);
var uri = new Uri(Assembly.GetCallingAssembly().EscapedCodeBase);
var file = new FileInfo(uri.LocalPath);
var currentDirectory = file.Directory;
var assemblyFiles = currentDirectory.GetFiles("*.dll");
var assemblies = assemblyFiles.Select(y => Assembly.LoadFile(y.FullName));
return assemblies;
}

private void AddAssemblyForType(Type model)
{
_declarationAssemblies.Add(model.Assembly);
if (model.IsGenericType)
{
model.GetGenericArguments().ToList().ForEach(AddAssemblyForType);
}
}
public string ClassName { get { return _className; } }

public CompilerParameters GetCompilerParameters()
{
var assemblieLocations = TypeResolver.DefaultAssemblies
.Union(_declarationAssemblies)
.Where(IsValidReference)
.GroupBy(an => an.Location)
.Select(an => an.First().Location)
.ToArray();

var assemblieLocations = DefaultAssemblies.Select(y => y.Location).ToArray();
_compilerParameters.ReferencedAssemblies.AddRange(assemblieLocations);

return _compilerParameters;
}

private static bool IsValidReference(Assembly assembly)
{
return ((Type.GetType("Mono.Runtime") == null) || !ExcludedReferencesOnMono.Any(assembly.Location.Contains));
}
}
}
1 change: 0 additions & 1 deletion src/Simple.Web.Razor/Simple.Web.Razor.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,6 @@
<Compile Include="SimpleRazorBuildProvider.cs" />
<Compile Include="SimpleTemplateBase.cs" />
<Compile Include="TypeNameTranslator.cs" />
<Compile Include="TypeResolver.cs" />
<Compile Include="DynamicDictionary.cs" />
<Compile Include="ViewNotFoundException.cs" />
</ItemGroup>
Expand Down
Loading