Skip to content

Commit 12c5233

Browse files
committed
Added Razor comparison example
1 parent d4cdf4b commit 12c5233

File tree

14 files changed

+541
-0
lines changed

14 files changed

+541
-0
lines changed

Web/AspNet/AspNet.sln

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
2+
Microsoft Visual Studio Solution File, Format Version 12.00
3+
# Visual Studio 14
4+
VisualStudioVersion = 14.0.25420.1
5+
MinimumVisualStudioVersion = 10.0.40219.1
6+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Legacy", "RazorComparison\Legacy\Legacy.csproj", "{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}"
7+
EndProject
8+
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "RazorComparison", "RazorComparison", "{D4BDA141-57D3-4EB8-A57F-A1427A0F2B39}"
9+
ProjectSection(SolutionItems) = preProject
10+
RazorComparison\Page.cshtml = RazorComparison\Page.cshtml
11+
EndProjectSection
12+
EndProject
13+
Project("{8BB2217D-0F2D-49D1-97BC-3654ED321F3B}") = "New", "RazorComparison\New\New.xproj", "{E16DDA96-402A-4D90-9ADE-9D3257193E1F}"
14+
EndProject
15+
Global
16+
GlobalSection(SolutionConfigurationPlatforms) = preSolution
17+
Debug|Any CPU = Debug|Any CPU
18+
Release|Any CPU = Release|Any CPU
19+
EndGlobalSection
20+
GlobalSection(ProjectConfigurationPlatforms) = postSolution
21+
{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
22+
{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}.Debug|Any CPU.Build.0 = Debug|Any CPU
23+
{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}.Release|Any CPU.ActiveCfg = Release|Any CPU
24+
{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}.Release|Any CPU.Build.0 = Release|Any CPU
25+
{E16DDA96-402A-4D90-9ADE-9D3257193E1F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
26+
{E16DDA96-402A-4D90-9ADE-9D3257193E1F}.Debug|Any CPU.Build.0 = Debug|Any CPU
27+
{E16DDA96-402A-4D90-9ADE-9D3257193E1F}.Release|Any CPU.ActiveCfg = Release|Any CPU
28+
{E16DDA96-402A-4D90-9ADE-9D3257193E1F}.Release|Any CPU.Build.0 = Release|Any CPU
29+
EndGlobalSection
30+
GlobalSection(SolutionProperties) = preSolution
31+
HideSolutionNode = FALSE
32+
EndGlobalSection
33+
GlobalSection(NestedProjects) = preSolution
34+
{DFD40DC4-09C7-4FCC-BF33-5E3908178C99} = {D4BDA141-57D3-4EB8-A57F-A1427A0F2B39}
35+
{E16DDA96-402A-4D90-9ADE-9D3257193E1F} = {D4BDA141-57D3-4EB8-A57F-A1427A0F2B39}
36+
EndGlobalSection
37+
EndGlobal
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<configuration>
3+
<startup>
4+
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
5+
</startup>
6+
</configuration>
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4+
<PropertyGroup>
5+
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6+
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7+
<ProjectGuid>{DFD40DC4-09C7-4FCC-BF33-5E3908178C99}</ProjectGuid>
8+
<OutputType>Exe</OutputType>
9+
<AppDesignerFolder>Properties</AppDesignerFolder>
10+
<RootNamespace>Legacy</RootNamespace>
11+
<AssemblyName>Legacy</AssemblyName>
12+
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
13+
<FileAlignment>512</FileAlignment>
14+
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
15+
<TargetFrameworkProfile />
16+
</PropertyGroup>
17+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
18+
<PlatformTarget>AnyCPU</PlatformTarget>
19+
<DebugSymbols>true</DebugSymbols>
20+
<DebugType>full</DebugType>
21+
<Optimize>false</Optimize>
22+
<OutputPath>bin\Debug\</OutputPath>
23+
<DefineConstants>DEBUG;TRACE</DefineConstants>
24+
<ErrorReport>prompt</ErrorReport>
25+
<WarningLevel>4</WarningLevel>
26+
</PropertyGroup>
27+
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
28+
<PlatformTarget>AnyCPU</PlatformTarget>
29+
<DebugType>pdbonly</DebugType>
30+
<Optimize>true</Optimize>
31+
<OutputPath>bin\Release\</OutputPath>
32+
<DefineConstants>TRACE</DefineConstants>
33+
<ErrorReport>prompt</ErrorReport>
34+
<WarningLevel>4</WarningLevel>
35+
</PropertyGroup>
36+
<ItemGroup>
37+
<Reference Include="System" />
38+
<Reference Include="System.Core" />
39+
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
40+
<HintPath>..\..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
41+
<Private>True</Private>
42+
</Reference>
43+
<Reference Include="System.Xml.Linq" />
44+
<Reference Include="System.Data.DataSetExtensions" />
45+
<Reference Include="Microsoft.CSharp" />
46+
<Reference Include="System.Data" />
47+
<Reference Include="System.Net.Http" />
48+
<Reference Include="System.Xml" />
49+
</ItemGroup>
50+
<ItemGroup>
51+
<Compile Include="LegacyRazor.cs" />
52+
<Compile Include="Properties\AssemblyInfo.cs" />
53+
</ItemGroup>
54+
<ItemGroup>
55+
<None Include="App.config" />
56+
<None Include="packages.config" />
57+
</ItemGroup>
58+
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
59+
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
60+
Other similar extension points exist, see Microsoft.Common.targets.
61+
<Target Name="BeforeBuild">
62+
</Target>
63+
<Target Name="AfterBuild">
64+
</Target>
65+
-->
66+
</Project>
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
using Microsoft.CSharp;
2+
using System;
3+
using System.CodeDom.Compiler;
4+
using System.IO;
5+
using System.Text;
6+
using System.Web.Razor;
7+
using System.Web.Razor.Generator;
8+
9+
namespace Legacy
10+
{
11+
class LegacyRazor
12+
{
13+
static void Main(string[] args)
14+
{
15+
Run();
16+
}
17+
18+
static void Run()
19+
{
20+
// ホスト作成
21+
var language = new CSharpRazorCodeLanguage();
22+
var host = new RazorEngineHost(language)
23+
{
24+
DefaultBaseClass = nameof(Legacy) + "." + nameof(LegacyTemplateBase),
25+
DefaultClassName = "Generated",
26+
DefaultNamespace = "RazorTemplate",
27+
// 生成されるメソッド名の指定(これはデフォルトと同じものを指定している)
28+
GeneratedClassContext = new GeneratedClassContext(
29+
nameof(LegacyTemplateBase.Execute),
30+
nameof(LegacyTemplateBase.Write),
31+
nameof(LegacyTemplateBase.WriteLiteral)
32+
)
33+
};
34+
// デフォルトで挿入する名前空間を追加
35+
host.NamespaceImports.Add(nameof(System));
36+
37+
var engine = new RazorTemplateEngine(host);
38+
using (var reader = new StreamReader(File.OpenRead("../../../Page.cshtml")))
39+
{
40+
// コードDOM生成
41+
var generatorResults = engine.GenerateCode(reader);
42+
System.CodeDom.CodeCompileUnit unit = generatorResults.GeneratedCode;
43+
var provider = new CSharpCodeProvider();
44+
45+
// 表示用
46+
provider.GenerateCodeFromCompileUnit(unit, Console.Out, new CodeGeneratorOptions());
47+
Console.WriteLine("------------------------------------------------------------------------");
48+
49+
// 使用アセンブリ参照
50+
var parameters = new CompilerParameters();
51+
parameters.ReferencedAssemblies.Add("System.Core.dll");
52+
parameters.ReferencedAssemblies.Add(typeof(LegacyTemplateBase).Assembly.Location);
53+
54+
// コンパイル
55+
var compilerResults = provider.CompileAssemblyFromDom(parameters, unit);
56+
57+
// 実行
58+
var typeName = host.DefaultNamespace + "." + host.DefaultClassName;
59+
var instance = compilerResults.CompiledAssembly.CreateInstance(typeName) as LegacyTemplateBase;
60+
var generatedString = instance.Generate();
61+
62+
// 結果表示
63+
Console.Write(generatedString);
64+
}
65+
}
66+
}
67+
68+
public abstract class LegacyTemplateBase
69+
{
70+
StringBuilder builder = new StringBuilder();
71+
72+
public void Write(object value)
73+
{
74+
builder.Append(value);
75+
}
76+
77+
public void WriteLiteral(string literal)
78+
{
79+
builder.Append(literal);
80+
}
81+
82+
public abstract void Execute();
83+
84+
public string Generate()
85+
{
86+
Execute();
87+
return builder.ToString();
88+
}
89+
}
90+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
using System.Reflection;
2+
using System.Runtime.CompilerServices;
3+
using System.Runtime.InteropServices;
4+
5+
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
6+
// アセンブリに関連付けられている情報を変更するには、
7+
// これらの属性値を変更してください。
8+
[assembly: AssemblyTitle("Legacy")]
9+
[assembly: AssemblyDescription("")]
10+
[assembly: AssemblyConfiguration("")]
11+
[assembly: AssemblyCompany("")]
12+
[assembly: AssemblyProduct("Legacy")]
13+
[assembly: AssemblyCopyright("Copyright © 2016")]
14+
[assembly: AssemblyTrademark("")]
15+
[assembly: AssemblyCulture("")]
16+
17+
// ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから
18+
// 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、
19+
// その型の ComVisible 属性を true に設定してください。
20+
[assembly: ComVisible(false)]
21+
22+
// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります
23+
[assembly: Guid("dfd40dc4-09c7-4fcc-bf33-5e3908178c99")]
24+
25+
// アセンブリのバージョン情報は次の 4 つの値で構成されています:
26+
//
27+
// メジャー バージョン
28+
// マイナー バージョン
29+
// ビルド番号
30+
// Revision
31+
//
32+
// すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を
33+
// 既定値にすることができます:
34+
// [assembly: AssemblyVersion("1.0.*")]
35+
[assembly: AssemblyVersion("1.0.0.0")]
36+
[assembly: AssemblyFileVersion("1.0.0.0")]
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<packages>
3+
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net461" />
4+
</packages>
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3+
<PropertyGroup>
4+
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">14.0</VisualStudioVersion>
5+
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
6+
</PropertyGroup>
7+
8+
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.Props" Condition="'$(VSToolsPath)' != ''" />
9+
<PropertyGroup Label="Globals">
10+
<ProjectGuid>e16dda96-402a-4d90-9ade-9d3257193e1f</ProjectGuid>
11+
<RootNamespace>New</RootNamespace>
12+
<BaseIntermediateOutputPath Condition="'$(BaseIntermediateOutputPath)'=='' ">.\obj</BaseIntermediateOutputPath>
13+
<OutputPath Condition="'$(OutputPath)'=='' ">.\bin\</OutputPath>
14+
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
15+
</PropertyGroup>
16+
17+
<PropertyGroup>
18+
<SchemaVersion>2.0</SchemaVersion>
19+
</PropertyGroup>
20+
<Import Project="$(VSToolsPath)\DotNet\Microsoft.DotNet.targets" Condition="'$(VSToolsPath)' != ''" />
21+
</Project>
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
using Microsoft.AspNetCore.Razor;
2+
using Microsoft.AspNetCore.Razor.CodeGenerators;
3+
using Microsoft.CodeAnalysis;
4+
using Microsoft.CodeAnalysis.CSharp;
5+
using System;
6+
using System.IO;
7+
using System.Reflection;
8+
using System.Runtime.Loader;
9+
using System.Text;
10+
using System.Threading.Tasks;
11+
12+
namespace New
13+
{
14+
public class NewRazor
15+
{
16+
public static void Main(string[] args)
17+
{
18+
Run().Wait();
19+
}
20+
21+
static async Task Run()
22+
{
23+
// ホスト生成
24+
var language = new CSharpRazorCodeLanguage();
25+
var host = new RazorEngineHost(language)
26+
{
27+
DefaultBaseClass = nameof(New) + "." + nameof(NewTemplateBase),
28+
DefaultClassName = "Generated",
29+
DefaultNamespace = "RazorTemplate",
30+
// 生成されるメソッド名の指定(これはデフォルトと同じものを指定している)
31+
GeneratedClassContext = new GeneratedClassContext(
32+
nameof(NewTemplateBase.ExecuteAsync),
33+
nameof(NewTemplateBase.Write),
34+
nameof(NewTemplateBase.WriteLiteral),
35+
new GeneratedTagHelperContext { }
36+
)
37+
};
38+
// デフォルトで挿入する名前空間を追加
39+
host.NamespaceImports.Add(nameof(System));
40+
host.NamespaceImports.Add(nameof(System) + "." + nameof(System.Threading) + "." + nameof(System.Threading.Tasks));
41+
42+
var engine = new RazorTemplateEngine(host);
43+
using (var reader = new StreamReader(File.OpenRead("../Page.cshtml")))
44+
{
45+
//ソースコード生成
46+
var generatorResults = engine.GenerateCode(reader);
47+
string source = generatorResults.GeneratedCode;
48+
49+
//表示用
50+
Console.Write(source);
51+
Console.WriteLine("------------------------------------------------------------------------");
52+
53+
var dllBase = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location);
54+
//使用アセンブリ参照
55+
var references = new MetadataReference[]
56+
{
57+
MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location),
58+
MetadataReference.CreateFromFile(dllBase + @"\mscorlib.dll"),
59+
MetadataReference.CreateFromFile(dllBase + @"\System.Runtime.dll"),
60+
MetadataReference.CreateFromFile(dllBase + @"\System.Linq.dll"),
61+
MetadataReference.CreateFromFile(dllBase + @"\System.Threading.Tasks.dll"),
62+
MetadataReference.CreateFromFile(typeof(NewTemplateBase).GetTypeInfo().Assembly.Location)
63+
};
64+
65+
//コンパイル
66+
var compilation = CSharpCompilation.Create("NewPage")
67+
.WithOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
68+
.AddReferences(references)
69+
.AddSyntaxTrees(CSharpSyntaxTree.ParseText(source));
70+
71+
using (var ms = new MemoryStream())
72+
{
73+
var result = compilation.Emit(ms);
74+
ms.Seek(0, SeekOrigin.Begin);
75+
var assembly = AssemblyLoadContext.Default.LoadFromStream(ms);
76+
77+
//実行
78+
var typeName = host.DefaultNamespace + "." + host.DefaultClassName;
79+
var instance = assembly.CreateInstance(typeName) as NewTemplateBase;// .GetMethod(nameof(NewTemplateBase.Execute))
80+
var generatedString = await instance.GenerateAsync();
81+
82+
//結果表示
83+
Console.Write(generatedString);
84+
}
85+
}
86+
}
87+
}
88+
89+
public abstract class NewTemplateBase
90+
{
91+
StringBuilder builder = new StringBuilder();
92+
93+
public void Write(object value)
94+
{
95+
builder.Append(value);
96+
}
97+
98+
public void WriteLiteral(string literal)
99+
{
100+
builder.Append(literal);
101+
}
102+
103+
public abstract Task ExecuteAsync();
104+
105+
public async Task<string> GenerateAsync()
106+
{
107+
await ExecuteAsync();
108+
return builder.ToString();
109+
}
110+
}
111+
}

0 commit comments

Comments
 (0)