<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>VibrantCode - Razor</title>
    <link>http://blog.andrewnurse.net/</link>
    <description>Oooh...pretty code</description>
    <language>en-us</language>
    <copyright>Andrew Nurse</copyright>
    <lastBuildDate>Mon, 02 Aug 2010 05:24:29 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.0.7226.0</generator>
    <managingEditor>andrew@andrewnurse.net</managingEditor>
    <webMaster>andrew@andrewnurse.net</webMaster>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=56056f45-920f-487c-ba80-0c53c3e44a97</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,56056f45-920f-487c-ba80-0c53c3e44a97.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,56056f45-920f-487c-ba80-0c53c3e44a97.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=56056f45-920f-487c-ba80-0c53c3e44a97</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of the features of Razor which hasn’t been discussed a lot is the Inline Template
feature.  Razor includes the ability to provide an inline Razor template as an
argument to a method.  At the moment, this is only used by the Grid helper in
ASP.Net Web Pages (and Scott Guthrie showed it back in his <a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx">original
blog post</a>).  However, we don't have much documentation on how to create your
own templated helpers yet, so I figured I'd talk a bit about it.
</p>
        <p>
First, let’s take a look at what code is generated when we use an inline template. 
I’ve written a sample templated helper called “Repeat” which just repeats the content
of the template a specified number of times (we'll take a look at the implementation
later).  The page that uses this helper looks something like this:
</p>
        <pre class="csharp" name="code">&lt;!DOCTYPE html&gt;
&lt;html&gt;
     &lt;head&gt;
         &lt;title&gt;Repeat Helper Demo&lt;/title&gt;
     &lt;/head&gt;
     &lt;body&gt;
         &lt;p&gt;Repeat Helper&lt;/p&gt;
         &lt;ul&gt;
             @Repeat(10, @&lt;li&gt;List Item&lt;/li&gt;);
         &lt;/ul&gt;
     &lt;/body&gt;
&lt;/html&gt;</pre>
        <p>
And when we run it, we get the following output:
</p>
        <p>
          <a href="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss1_2.png">
            <img style="border-width: 0px; display: inline;" title="Screen shot of rendered HTML." alt="Screen shot of rendered HTML." src="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss1_thumb.png" width="385" border="0" height="400" />
          </a>
        </p>
        <p>
Let’s take a look at the implementation of “Repeat”.  I wrote it inline in the
page in this case, but you could just as easily write it in a static class in App_Code
and reference it that way.  In Razor, the “@functions” block lets you write code
that will be injected as-is into the body of the generated class.
</p>
        <pre class="csharp" name="code">@using System.Text;
@functions {
      public static IHtmlString Repeat(int times, Func&lt;int, object&gt; template) {
           StringBuilder builder = new StringBuilder();
          for(int i = 0; i &lt; times; i++) {
              builder.Append(template(i));
          }
          return new HtmlString(builder.ToString());
      }
}</pre>
        <p>
So, the template is being passed in as a Func&lt;int, object&gt; and when we invoke
it, we get back the result of running the template.  But, if you look at line
6, you’ll notice we’re passing in an argument to the template function.  Let’s
take a look at the C# that is generated when we write a call to Repeat.  Here’s
the generated code to match the Razor code in the first code listing:
</p>
        <pre class="csharp" name="code">this.Write(Repeat(10,item =&gt; new Microsoft.WebPages.Helpers.HelperResult(__writer =&gt; {
     @__writer.Write(" ");
     @__writer.Write("&lt;li&gt;List Item&lt;/li&gt;");
})));</pre>
        <p>
It’s a little complex looking, but essentially, what’s happening is that we’re writing
out a lambda which accepts a single parameter called “item” (the type of which is
determined by the method you’re passing it to).  When that lambda runs, we construct
and return a HelperResult.  HelperResult is a class defined in the ASP.Net Web
Pages framework, and it’s essentially a wrapper around yet another delegate which
writes text to a TextWriter.  Think of it as a mini Razor template, when you
invoke the delegate, it writes the content of the template.  The advantage of
wrapping the delegate up in the HelperResult class is that we can treat it just like
a string in most places since it overrides ToString to return the result of executing
the template.
</p>
        <p>
The “item” parameter is used in helpers like the Grid helper to provide the current
data item to the template so that it can be used.  The Repeat helper passes in
the iteration number as this parameter, which we can access from within the template
by using “@item”.  For example:
</p>
        <pre class="csharp" name="code">@Repeat(10, @&lt;li&gt;List Item #@item&lt;/li&gt;);</pre>
        <p>
Which will render:
</p>
        <p>
          <a href="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss2_2.png">
            <img style="border: 0px none; display: inline;" title="ss2" alt="ss2" src="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss2_thumb.png" width="324" border="0" height="373" />
          </a>
        </p>
        <p>
In summary, if you want to use Razor templates in your helper methods, just add a
parameter with the type Func&lt;<em>?</em>, object&gt; where <em>?</em> can be <strong>any</strong> type
you want.  As an interesting little exercise, try converting the Repeat helper
to take an IEnumerable&lt;T&gt; and pass each item of that enumerable to the template,
rendering the result.<br /></p>
        <p>
I've uploaded the Razor file containing my sample helper here: <a href="http://blog.andrewnurse.net/content/binary/RepeatHelper.cshtml.txt">RepeatHelper.cshtml.txt
(.56 KB)</a> (Note: To avoid issues with file types on my hoster, it has a .txt extension,
just remove that and you're good to go!)
</p>
        <p>
Please feel free to ask questions in the comments, or by emailing me at andrew AT
andrewnurse DOT net.  I'm also on twitter at @anurse and I keep an eye on the
"razor" tag on <a href="http://www.stackoverflow.com">StackOverflow</a> so there's
no shortage of ways to ask!
</p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=56056f45-920f-487c-ba80-0c53c3e44a97" />
      </body>
      <title>Inside Razor - Part 3 - Templates</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,56056f45-920f-487c-ba80-0c53c3e44a97.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/08/02/InsideRazorPart3Templates.aspx</link>
      <pubDate>Mon, 02 Aug 2010 05:24:29 GMT</pubDate>
      <description>&lt;p&gt;
One of the features of Razor which hasn’t been discussed a lot is the Inline Template
feature.&amp;nbsp; Razor includes the ability to provide an inline Razor template as an
argument to a method.&amp;nbsp; At the moment, this is only used by the Grid helper in
ASP.Net Web Pages (and Scott Guthrie showed it back in his &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx"&gt;original
blog post&lt;/a&gt;).&amp;nbsp; However, we don't have much documentation on how to create your
own templated helpers yet, so I figured I'd talk a bit about it.
&lt;/p&gt;
&lt;p&gt;
First, let’s take a look at what code is generated when we use an inline template.&amp;nbsp;
I’ve written a sample templated helper called “Repeat” which just repeats the content
of the template a specified number of times (we'll take a look at the implementation
later).&amp;nbsp; The page that uses this helper looks something like this:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;!DOCTYPE html&amp;gt;
&amp;lt;html&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;head&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;title&amp;gt;Repeat Helper Demo&amp;lt;/title&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/head&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;body&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;p&amp;gt;Repeat Helper&amp;lt;/p&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;ul&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; @Repeat(10, @&amp;lt;li&amp;gt;List Item&amp;lt;/li&amp;gt;);
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/ul&amp;gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;lt;/body&amp;gt;
&amp;lt;/html&amp;gt;&lt;/pre&gt;
&lt;p&gt;
And when we run it, we get the following output:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss1_2.png"&gt;&lt;img style="border-width: 0px; display: inline;" title="Screen shot of rendered HTML." alt="Screen shot of rendered HTML." src="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss1_thumb.png" width="385" border="0" height="400"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Let’s take a look at the implementation of “Repeat”.&amp;nbsp; I wrote it inline in the
page in this case, but you could just as easily write it in a static class in App_Code
and reference it that way.&amp;nbsp; In Razor, the “@functions” block lets you write code
that will be injected as-is into the body of the generated class.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@using System.Text;
@functions {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; public static IHtmlString Repeat(int times, Func&amp;lt;int, object&amp;gt; template) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; StringBuilder builder = new StringBuilder();
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; for(int i = 0; i &amp;lt; times; i++) {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; builder.Append(template(i));
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; return new HtmlString(builder.ToString());
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
}&lt;/pre&gt;
&lt;p&gt;
So, the template is being passed in as a Func&amp;lt;int, object&amp;gt; and when we invoke
it, we get back the result of running the template.&amp;nbsp; But, if you look at line
6, you’ll notice we’re passing in an argument to the template function.&amp;nbsp; Let’s
take a look at the C# that is generated when we write a call to Repeat.&amp;nbsp; Here’s
the generated code to match the Razor code in the first code listing:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;this.Write(Repeat(10,item =&amp;gt; new Microsoft.WebPages.Helpers.HelperResult(__writer =&amp;gt; {
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; @__writer.Write(" ");
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; @__writer.Write("&amp;lt;li&amp;gt;List Item&amp;lt;/li&amp;gt;");
})));&lt;/pre&gt;
&lt;p&gt;
It’s a little complex looking, but essentially, what’s happening is that we’re writing
out a lambda which accepts a single parameter called “item” (the type of which is
determined by the method you’re passing it to).&amp;nbsp; When that lambda runs, we construct
and return a HelperResult.&amp;nbsp; HelperResult is a class defined in the ASP.Net Web
Pages framework, and it’s essentially a wrapper around yet another delegate which
writes text to a TextWriter.&amp;nbsp; Think of it as a mini Razor template, when you
invoke the delegate, it writes the content of the template.&amp;nbsp; The advantage of
wrapping the delegate up in the HelperResult class is that we can treat it just like
a string in most places since it overrides ToString to return the result of executing
the template.
&lt;/p&gt;
&lt;p&gt;
The “item” parameter is used in helpers like the Grid helper to provide the current
data item to the template so that it can be used.&amp;nbsp; The Repeat helper passes in
the iteration number as this parameter, which we can access from within the template
by using “@item”.&amp;nbsp; For example:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@Repeat(10, @&amp;lt;li&amp;gt;List Item #@item&amp;lt;/li&amp;gt;);&lt;/pre&gt;
&lt;p&gt;
Which will render:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss2_2.png"&gt;&lt;img style="border: 0px none; display: inline;" title="ss2" alt="ss2" src="http://blog.andrewnurse.net/content/binary/WindowsLiveWriter/InsideRazorPart3Templates_13B11/ss2_thumb.png" width="324" border="0" height="373"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
In summary, if you want to use Razor templates in your helper methods, just add a
parameter with the type Func&amp;lt;&lt;em&gt;?&lt;/em&gt;, object&amp;gt; where &lt;em&gt;?&lt;/em&gt; can be &lt;strong&gt;any&lt;/strong&gt; type
you want.&amp;nbsp; As an interesting little exercise, try converting the Repeat helper
to take an IEnumerable&amp;lt;T&amp;gt; and pass each item of that enumerable to the template,
rendering the result.&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
I've uploaded the Razor file containing my sample helper here: &lt;a href="http://blog.andrewnurse.net/content/binary/RepeatHelper.cshtml.txt"&gt;RepeatHelper.cshtml.txt
(.56 KB)&lt;/a&gt; (Note: To avoid issues with file types on my hoster, it has a .txt extension,
just remove that and you're good to go!)
&lt;/p&gt;
&lt;p&gt;
Please feel free to ask questions in the comments, or by emailing me at andrew AT
andrewnurse DOT net.&amp;nbsp; I'm also on twitter at @anurse and I keep an eye on the
"razor" tag on &lt;a href="http://www.stackoverflow.com"&gt;StackOverflow&lt;/a&gt; so there's
no shortage of ways to ask!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=56056f45-920f-487c-ba80-0c53c3e44a97" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,56056f45-920f-487c-ba80-0c53c3e44a97.aspx</comments>
      <category>ASP.Net</category>
      <category>Razor</category>
    </item>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=6acc0b07-0db5-4353-b375-fbe60a209bb1</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,6acc0b07-0db5-4353-b375-fbe60a209bb1.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,6acc0b07-0db5-4353-b375-fbe60a209bb1.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=6acc0b07-0db5-4353-b375-fbe60a209bb1</wfw:commentRss>
      <slash:comments>13</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When Scott Guthrie originally blogged about Razor, he mentioned that it was fully
hostable outside of ASP.Net.  The engine itself is not quite as detached from
System.Web as we’d like, but it’s close and we’re going to get it way closer in the
next release.
</p>
        <p>
Having said that, you can still host Razor outside of the ASP.Net pipeline with the
current beta! It’s a little trickier, and you do technically need to reference System.Web. 
I’ve written a sample console app that I’m attaching to this post called “rzrc” which
takes in  a .cshtml or .vbhtml Razor file and runs it through the parser and
code generator to produce a .cs or .vb file.  I’ll walk through the main logic
here and go over what each section does.
</p>
        <p>
However, I was not the first to do this! Full credit for that goes to <a href="http://thegsharp.wordpress.com/">Gustavo
Machado</a>, who wrote <a href="http://thegsharp.wordpress.com/2010/07/07/using-razor-from-a-console-application/">an
excellent post</a> in which he used Reflector to work out how to run the Razor parser
and code generator.  Well done Gustavo!  There are a few things that this
version does that Gustavo’s doesn’t, such as cleaning up the Web-related stuff in
the generated code and selecting the language based on the Code Language, but he basically
hit it spot on!
</p>
        <p>
The first thing my console app does is get the input file name, extract the extension
and look up what Razor Code Language it uses.  This is done using the CodeLanguageService
class, which is part of the Razor APIs:
</p>
        <pre class="csharp" name="code">CodeLanguageService languageService = CodeLanguageService.GetServiceByExtension(extension);
if (languageService == null) {
    Console.WriteLine("{0} is not a Razor code language", extension);
    return;
}</pre>
        <p>
Then, we fire up the parser and the code generator.  A CodeLanguageService is
basically a factory for constructing a Code Parser, to parse the code blocks after
an “@” and a matching Code Generator to write the final C# or VB class.
</p>
        <pre class="csharp" name="code">InlinePageParser parser = new InlinePageParser(languageService.CreateCodeParser(), new HtmlMarkupParser());
CodeGenerator codeGenerator = 
    languageService.CreateCodeGeneratorParserListener(className,
                                                        rootNamespaceName: "Template", 
                                                        applicationTypeName: "object", 
                                                        inputFileName, 
                                                        baseClass: "System.Object");</pre>
        <p>
When you run the Razor Parser, you must provide it with an object implementing IParserConsumer. 
This interface has callbacks which the parser will call when it encounters various
Razor constructs (more details on the Razor parse tree later).  CodeGenerator
implements this interface and responds to the these callbacks by generating code. 
However, it does nothing with the errors, so in the console app, I’ve written a very
simple IParserConsumer called CustomParserConsumer which wraps the code generator
and outputs errors to the console.  I won’t put the code here, but it’s in the
sample, so take a look there if you’re interested.
</p>
        <p>
Now that we’ve got all the objects we need, we can actually run the parser over the
input
</p>
        <pre class="csharp" name="code">CustomParserConsumer consumer = new CustomParserConsumer() { CodeGenerator = codeGenerator };
using (StreamReader reader = new StreamReader(inputFileName)) {
    parser.Parse(reader, consumer);
}</pre>
        <p>
Once Parse returns, the Code Generator will have built a CodeDOM tree representing
the generated code during the callbacks, so we know that our code is ready to go. 
Right now, the Code Generator adds in some web specific things.  For example,
when we constructed the Code Gneerator above, we gave it an “applicationTypeName”
which (in a web context) is the type name of the class defined in Global.asax, if
there is one.  Since we are trying to generate a template that isn’t related
to the web, we can get the CodeDOM tree from the Code Generator and remove these things.
</p>
        <pre class="csharp" name="code">codeGenerator.GeneratedCode.Namespaces[0].Types[0].Members.RemoveAt(0);
codeGenerator.GeneratedCode.Namespaces[0].Types[0].BaseTypes.Clear();
codeGenerator.GeneratedCode.Namespaces[0].Imports.Clear();</pre>
        <p>
Finally, we use the CodeDOM to write the code to a C# or VB class file (provider is
a CodeDomProvider from System.CodeDom.Compiler):
</p>
        <pre class="csharp" name="code">using (StreamWriter writer = new StreamWriter(outputFile)) {
    provider.GenerateCodeFromCompileUnit(codeGenerator.GeneratedCode, writer, new CodeDom.CodeGeneratorOptions());
}</pre>
        <p>
And we’re done!  This is definitely more complicated than we’d like, but there
are plans to simplify this API significantly in future releases.  For the most
part, all we’ve done is left the methods our ASP.Net Build Provider uses open and
accessible.  I wouldn’t bet on these APIs staying around too long, but any API
changes from here on should be simplifications.  For now though, check out the
sample I’ve attached and play around!  Note that you must have WebMatrix installed
to use the sample.  
</p>
        <p>
I’ve put some comments in which start with “EXT” which contain tips on how to extend
this code to your own use.  Please feel free to take this code and use it absolutely
anywhere you want!  Let me know how your using Razor by either tweeting me at
@anurse or email me at andrew AT andrewnurse DOT net.
</p>
        <p>
Download the console app here: <a href="http://blog.andrewnurse.net/content/binary/rzrc.zip">rzrc.zip
(3.46 KB)</a></p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=6acc0b07-0db5-4353-b375-fbe60a209bb1" />
      </body>
      <title>Using the Razor parser outside of ASP.Net</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,6acc0b07-0db5-4353-b375-fbe60a209bb1.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/07/22/UsingTheRazorParserOutsideOfASPNet.aspx</link>
      <pubDate>Thu, 22 Jul 2010 06:07:53 GMT</pubDate>
      <description>&lt;p&gt;
When Scott Guthrie originally blogged about Razor, he mentioned that it was fully
hostable outside of ASP.Net.&amp;nbsp; The engine itself is not quite as detached from
System.Web as we’d like, but it’s close and we’re going to get it way closer in the
next release.
&lt;/p&gt;
&lt;p&gt;
Having said that, you can still host Razor outside of the ASP.Net pipeline with the
current beta! It’s a little trickier, and you do technically need to reference System.Web.&amp;nbsp;
I’ve written a sample console app that I’m attaching to this post called “rzrc” which
takes in&amp;nbsp; a .cshtml or .vbhtml Razor file and runs it through the parser and
code generator to produce a .cs or .vb file.&amp;nbsp; I’ll walk through the main logic
here and go over what each section does.
&lt;/p&gt;
&lt;p&gt;
However, I was not the first to do this! Full credit for that goes to &lt;a href="http://thegsharp.wordpress.com/"&gt;Gustavo
Machado&lt;/a&gt;, who wrote &lt;a href="http://thegsharp.wordpress.com/2010/07/07/using-razor-from-a-console-application/"&gt;an
excellent post&lt;/a&gt; in which he used Reflector to work out how to run the Razor parser
and code generator.&amp;nbsp; Well done Gustavo!&amp;nbsp; There are a few things that this
version does that Gustavo’s doesn’t, such as cleaning up the Web-related stuff in
the generated code and selecting the language based on the Code Language, but he basically
hit it spot on!
&lt;/p&gt;
&lt;p&gt;
The first thing my console app does is get the input file name, extract the extension
and look up what Razor Code Language it uses.&amp;nbsp; This is done using the CodeLanguageService
class, which is part of the Razor APIs:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;CodeLanguageService languageService = CodeLanguageService.GetServiceByExtension(extension);
if (languageService == null) {
    Console.WriteLine("{0} is not a Razor code language", extension);
    return;
}&lt;/pre&gt;
&lt;p&gt;
Then, we fire up the parser and the code generator.&amp;nbsp; A CodeLanguageService is
basically a factory for constructing a Code Parser, to parse the code blocks after
an “@” and a matching Code Generator to write the final C# or VB class.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;InlinePageParser parser = new InlinePageParser(languageService.CreateCodeParser(), new HtmlMarkupParser());
CodeGenerator codeGenerator = 
    languageService.CreateCodeGeneratorParserListener(className,
                                                        rootNamespaceName: "Template", 
                                                        applicationTypeName: "object", 
                                                        inputFileName, 
                                                        baseClass: "System.Object");&lt;/pre&gt;
&lt;p&gt;
When you run the Razor Parser, you must provide it with an object implementing IParserConsumer.&amp;nbsp;
This interface has callbacks which the parser will call when it encounters various
Razor constructs (more details on the Razor parse tree later).&amp;nbsp; CodeGenerator
implements this interface and responds to the these callbacks by generating code.&amp;nbsp;
However, it does nothing with the errors, so in the console app, I’ve written a very
simple IParserConsumer called CustomParserConsumer which wraps the code generator
and outputs errors to the console.&amp;nbsp; I won’t put the code here, but it’s in the
sample, so take a look there if you’re interested.
&lt;/p&gt;
&lt;p&gt;
Now that we’ve got all the objects we need, we can actually run the parser over the
input
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;CustomParserConsumer consumer = new CustomParserConsumer() { CodeGenerator = codeGenerator };
using (StreamReader reader = new StreamReader(inputFileName)) {
    parser.Parse(reader, consumer);
}&lt;/pre&gt;
&lt;p&gt;
Once Parse returns, the Code Generator will have built a CodeDOM tree representing
the generated code during the callbacks, so we know that our code is ready to go.&amp;nbsp;
Right now, the Code Generator adds in some web specific things.&amp;nbsp; For example,
when we constructed the Code Gneerator above, we gave it an “applicationTypeName”
which (in a web context) is the type name of the class defined in Global.asax, if
there is one.&amp;nbsp; Since we are trying to generate a template that isn’t related
to the web, we can get the CodeDOM tree from the Code Generator and remove these things.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;codeGenerator.GeneratedCode.Namespaces[0].Types[0].Members.RemoveAt(0);
codeGenerator.GeneratedCode.Namespaces[0].Types[0].BaseTypes.Clear();
codeGenerator.GeneratedCode.Namespaces[0].Imports.Clear();&lt;/pre&gt;
&lt;p&gt;
Finally, we use the CodeDOM to write the code to a C# or VB class file (provider is
a CodeDomProvider from System.CodeDom.Compiler):
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;using (StreamWriter writer = new StreamWriter(outputFile)) {
    provider.GenerateCodeFromCompileUnit(codeGenerator.GeneratedCode, writer, new CodeDom.CodeGeneratorOptions());
}&lt;/pre&gt;
&lt;p&gt;
And we’re done!&amp;nbsp; This is definitely more complicated than we’d like, but there
are plans to simplify this API significantly in future releases.&amp;nbsp; For the most
part, all we’ve done is left the methods our ASP.Net Build Provider uses open and
accessible.&amp;nbsp; I wouldn’t bet on these APIs staying around too long, but any API
changes from here on should be simplifications.&amp;nbsp; For now though, check out the
sample I’ve attached and play around!&amp;nbsp; Note that you must have WebMatrix installed
to use the sample.&amp;nbsp; 
&lt;/p&gt;
&lt;p&gt;
I’ve put some comments in which start with “EXT” which contain tips on how to extend
this code to your own use.&amp;nbsp; Please feel free to take this code and use it absolutely
anywhere you want!&amp;nbsp; Let me know how your using Razor by either tweeting me at
@anurse or email me at andrew AT andrewnurse DOT net.
&lt;/p&gt;
&lt;p&gt;
Download the console app here: &lt;a href="http://blog.andrewnurse.net/content/binary/rzrc.zip"&gt;rzrc.zip
(3.46 KB)&lt;/a&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=6acc0b07-0db5-4353-b375-fbe60a209bb1" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,6acc0b07-0db5-4353-b375-fbe60a209bb1.aspx</comments>
      <category>ASP.Net</category>
      <category>Microsoft</category>
      <category>Razor</category>
    </item>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=89b7bd90-52d7-4d49-b87d-4e888f285b4c</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,89b7bd90-52d7-4d49-b87d-4e888f285b4c.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,89b7bd90-52d7-4d49-b87d-4e888f285b4c.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=89b7bd90-52d7-4d49-b87d-4e888f285b4c</wfw:commentRss>
      <slash:comments>12</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is part 2 of my Inside Razor series.  Read Part 1 <a href="http://blog.andrewnurse.net/2010/07/05/InsideRazorNdashPart1NdashRecursivePingPong.aspx">here</a>.
</p>
        <p>
In my previous post, I glossed over one line in my sample:
</p>
        <pre class="csharp" name="code">&lt;li&gt;@p.Name ($@p.Price)&lt;/li&gt;</pre>
        <p>
Well, it's finally time to get in to how this is parsed!  So, to recap from last
time, when we see the “&lt;li&gt;” here, we know that we are parsing a block of markup
which ends at the “&lt;/li&gt;”.  The markup parser scans forward until it finds
the end tag, but before it reaches it, it sees an “@”.  So, just as with “@foreach”,
it switches to the code parser.
</p>
        <p>
This is where things get a bit different.  The C# code parser looks at that first
identifier: “p” and checks its internal list of C# keywords.  Of course, “p”
is not a C# keyword, so the C# code parser enters “Implicit Expression” mode. 
The algorithm for parsing implicit expressions is something like the following:
</p>
        <ol>
          <li>
First, <strong><em>Read </em></strong>an identifier 
</li>
          <li>
Is the next character a “(“ or “[“? 
<ul><li>
Yes - <strong><em>Read</em></strong> to the matching “)” or '”]”, then <strong><em>Go
To</em></strong>2 
</li><li>
No – <strong><em>Continue</em></strong> to 3 
</li></ul></li>
          <li>
Is the next character a “.”? 
<ul><li>
Yes – <strong><em>Continue</em></strong> to 4 
</li><li>
No – <strong><em>End</em></strong> of Expression 
</li></ul></li>
          <li>
Is the character AFTER the “.” a valid start character for a C# identifier? 
<ul><li>
Yes – <strong><em>Read</em></strong>the “.” and <strong><em>Go To</em></strong>1 
</li><li>
No – <u>DO NOT Read</u> the “.”, and <em><strong>End</strong></em> the Expression 
</li></ul></li>
        </ol>
        <p>
The high-level overview of this algorithm is that an implicit expression is an identifier,
followed by any number of method calls (“()”), indexing expressions (“[]”) and member
access expressions (“.”).  And, whitespace is <strong>not allowed</strong> (except
for within “()” or “[]”).  So for example, these are all valid implicit expressions
in Razor:
</p>
        <pre class="csharp" name="code">@p.Name
@p.Name.ToString()
@p.Name.ToString()[6 - 2]
@p.Name.Replace(“ASPX”, “Razor”)[i++]</pre>
        <p>
However, the following are not valid, and the second section (after the arrow, “==&gt;”)
is the only part that would be considered part of the expression by Razor:
</p>
        <pre class="csharp" name="code">@1 + 1 ==&gt; @
@p++ ==&gt; @p
@p    .   Name ==&gt; @p
@p.Name.Length – 1 ==&gt; @p.Name.Length</pre>
        <p>
This is why we have another syntax for expressions: “@(…)”.  This syntax allows
anything you want within the “()”.  So, you can write all of the previous examples
using that syntax as an escape-hatch:
</p>
        <pre class="csharp" name="code">@(1 + 1) 
@(p++) 
@(p    .   Name) 
@(p.Name.Length - 1)</pre>
        <p>
Once we’ve identified the expression, we pass it along to our code generator. 
When generating the code for “@foreach () { … }”, we just dump that code into the
generated C# class as-is, but when we identify an expression (either implicit or explicit)
we do something a little different.  You probably noticed that unlike ASPX, there
is only one control construct: “@”, there is no “@=” to distinguish code that we run
vs. expressions that we render the value of.  This is where some of the magic
of Razor comes in.  If we see “@foreach” for example, we know that “foreach”
is a C# keyword, so that block is written as a statement to be executed.  When
we see “@p.Name” or “@(1 + 1)”, we know that they are expressions, so after executing
them, we render the result.  So basically:
</p>
        <ul>
          <li>
@if, @switch, @try, @foreach, @for, etc. are equivalent to “&lt;% %&gt;” 
</li>
          <li>
@p.Name, @(p++), @(1 + 1), etc. are equivalent to “&lt;%: %&gt;” 
</li>
        </ul>
        <p>
Another side note is that expressions are equivalent to “&lt;%:” and <strong>NOT </strong>“&lt;%=”. 
We made a decision in Razor that <strong>HTML encoding should be the default</strong>,
and that if you want to write unencoded strings, you can use the IHtmlString interface
that has been <a href="http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx">blogged
about</a> before.
</p>
        <p>
So, with all that background, we can quickly jump back to our initial sample:
</p>
        <pre class="csharp" name="code">&lt;li&gt;@p.Name ($@p.Price)&lt;/li&gt;</pre>
        <p>
When we see “@p.Name” we identify that as an expression, but the space before the
“(“ stops us from interpreting it as a method call.  Then “ ($” are all markup
and when we see the “@”, we interpret “@p.Price” as an expression and stop at the
“)”.
</p>
        <p>
So there’s a quick overview of how Razor identifies and parses expressions. 
In my next post I’m going to discuss hosting the Razor parser outside of ASP.Net. 
As before, please feel free to leave comments if you have questions, or send me a
tweet (@anurse) or an email (andrew AT andrewnurse DOT net).
</p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=89b7bd90-52d7-4d49-b87d-4e888f285b4c" />
      </body>
      <title>Inside Razor - Part 2 - Expressions</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,89b7bd90-52d7-4d49-b87d-4e888f285b4c.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/07/12/InsideRazorPart2Expressions.aspx</link>
      <pubDate>Mon, 12 Jul 2010 23:57:09 GMT</pubDate>
      <description>&lt;p&gt;
This is part 2 of my Inside Razor series.&amp;#160; Read Part 1 &lt;a href="http://blog.andrewnurse.net/2010/07/05/InsideRazorNdashPart1NdashRecursivePingPong.aspx"&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In my previous post, I glossed over one line in my sample:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;li&amp;gt;@p.Name ($@p.Price)&amp;lt;/li&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Well, it's finally time to get in to how this is parsed!&amp;#160; So, to recap from last
time, when we see the “&amp;lt;li&amp;gt;” here, we know that we are parsing a block of markup
which ends at the “&amp;lt;/li&amp;gt;”.&amp;#160; The markup parser scans forward until it finds
the end tag, but before it reaches it, it sees an “@”.&amp;#160; So, just as with “@foreach”,
it switches to the code parser.
&lt;/p&gt;
&lt;p&gt;
This is where things get a bit different.&amp;#160; The C# code parser looks at that first
identifier: “p” and checks its internal list of C# keywords.&amp;#160; Of course, “p”
is not a C# keyword, so the C# code parser enters “Implicit Expression” mode.&amp;#160;
The algorithm for parsing implicit expressions is something like the following:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
First, &lt;strong&gt;&lt;em&gt;Read &lt;/em&gt;&lt;/strong&gt;an identifier 
&lt;/li&gt;
&lt;li&gt;
Is the next character a “(“ or “[“? 
&lt;ul&gt;
&lt;li&gt;
Yes - &lt;strong&gt;&lt;em&gt;Read&lt;/em&gt;&lt;/strong&gt; to the matching “)” or '”]”, then &lt;strong&gt;&lt;em&gt;Go
To&lt;/em&gt; &lt;/strong&gt;2 
&lt;/li&gt;
&lt;li&gt;
No – &lt;strong&gt;&lt;em&gt;Continue&lt;/em&gt;&lt;/strong&gt; to 3 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Is the next character a “.”? 
&lt;ul&gt;
&lt;li&gt;
Yes – &lt;strong&gt;&lt;em&gt;Continue&lt;/em&gt;&lt;/strong&gt; to 4 
&lt;/li&gt;
&lt;li&gt;
No – &lt;strong&gt;&lt;em&gt;End&lt;/em&gt;&lt;/strong&gt; of Expression 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
Is the character AFTER the “.” a valid start character for a C# identifier? 
&lt;ul&gt;
&lt;li&gt;
Yes – &lt;strong&gt;&lt;em&gt;Read&lt;/em&gt; &lt;/strong&gt;the “.” and &lt;strong&gt;&lt;em&gt;Go To&lt;/em&gt; &lt;/strong&gt;1 
&lt;/li&gt;
&lt;li&gt;
No – &lt;u&gt;DO NOT Read&lt;/u&gt; the “.”, and &lt;em&gt;&lt;strong&gt;End&lt;/strong&gt;&lt;/em&gt; the Expression 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The high-level overview of this algorithm is that an implicit expression is an identifier,
followed by any number of method calls (“()”), indexing expressions (“[]”) and member
access expressions (“.”).&amp;#160; And, whitespace is &lt;strong&gt;not allowed&lt;/strong&gt; (except
for within “()” or “[]”).&amp;#160; So for example, these are all valid implicit expressions
in Razor:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@p.Name
@p.Name.ToString()
@p.Name.ToString()[6 - 2]
@p.Name.Replace(“ASPX”, “Razor”)[i++]&lt;/pre&gt;
&lt;p&gt;
However, the following are not valid, and the second section (after the arrow, “==&amp;gt;”)
is the only part that would be considered part of the expression by Razor:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@1 + 1 ==&amp;gt; @
@p++ ==&amp;gt; @p
@p    .   Name ==&amp;gt; @p
@p.Name.Length – 1 ==&amp;gt; @p.Name.Length&lt;/pre&gt;
&lt;p&gt;
This is why we have another syntax for expressions: “@(…)”.&amp;#160; This syntax allows
anything you want within the “()”.&amp;#160; So, you can write all of the previous examples
using that syntax as an escape-hatch:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@(1 + 1) 
@(p++) 
@(p    .   Name) 
@(p.Name.Length - 1)&lt;/pre&gt;
&lt;p&gt;
Once we’ve identified the expression, we pass it along to our code generator.&amp;#160;
When generating the code for “@foreach () { … }”, we just dump that code into the
generated C# class as-is, but when we identify an expression (either implicit or explicit)
we do something a little different.&amp;#160; You probably noticed that unlike ASPX, there
is only one control construct: “@”, there is no “@=” to distinguish code that we run
vs. expressions that we render the value of.&amp;#160; This is where some of the magic
of Razor comes in.&amp;#160; If we see “@foreach” for example, we know that “foreach”
is a C# keyword, so that block is written as a statement to be executed.&amp;#160; When
we see “@p.Name” or “@(1 + 1)”, we know that they are expressions, so after executing
them, we render the result.&amp;#160; So basically:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
@if, @switch, @try, @foreach, @for, etc. are equivalent to “&amp;lt;% %&amp;gt;” 
&lt;/li&gt;
&lt;li&gt;
@p.Name, @(p++), @(1 + 1), etc. are equivalent to “&amp;lt;%: %&amp;gt;” 
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Another side note is that expressions are equivalent to “&amp;lt;%:” and &lt;strong&gt;NOT &lt;/strong&gt;“&amp;lt;%=”.&amp;#160;
We made a decision in Razor that &lt;strong&gt;HTML encoding should be the default&lt;/strong&gt;,
and that if you want to write unencoded strings, you can use the IHtmlString interface
that has been &lt;a href="http://haacked.com/archive/2009/09/25/html-encoding-code-nuggets.aspx"&gt;blogged
about&lt;/a&gt; before.
&lt;/p&gt;
&lt;p&gt;
So, with all that background, we can quickly jump back to our initial sample:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;li&amp;gt;@p.Name ($@p.Price)&amp;lt;/li&amp;gt;&lt;/pre&gt;
&lt;p&gt;
When we see “@p.Name” we identify that as an expression, but the space before the
“(“ stops us from interpreting it as a method call.&amp;#160; Then “ ($” are all markup
and when we see the “@”, we interpret “@p.Price” as an expression and stop at the
“)”.
&lt;/p&gt;
&lt;p&gt;
So there’s a quick overview of how Razor identifies and parses expressions.&amp;#160;
In my next post I’m going to discuss hosting the Razor parser outside of ASP.Net.&amp;#160;
As before, please feel free to leave comments if you have questions, or send me a
tweet (@anurse) or an email (andrew AT andrewnurse DOT net).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=89b7bd90-52d7-4d49-b87d-4e888f285b4c" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,89b7bd90-52d7-4d49-b87d-4e888f285b4c.aspx</comments>
      <category>ASP.Net</category>
      <category>Razor</category>
    </item>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=884ea228-40cd-43c7-8620-9ac0af497e9a</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,884ea228-40cd-43c7-8620-9ac0af497e9a.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,884ea228-40cd-43c7-8620-9ac0af497e9a.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=884ea228-40cd-43c7-8620-9ac0af497e9a</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Scott Guthrie just announced the first
beta release of Microsoft WebMatrix.  I'll leave you to check out <a href="http://weblogs.asp.net/scottgu/archive/2010/07/06/introducing-webmatrix.aspx">his
blog post</a> to find out more.<br /><br />
This is also your <b>first chance</b> to try out Razor.  We haven't released
the MVC View Engine for Razor, but WebMatrix includes ASP.Net Web Pages, a simple
page model that uses Razor syntax.  After installing WebMatrix, just create a
new site, drop a CSHTML file in it, put some code in and go!<br /><br />
I'll post more details later, but for now, check out the post and play with the bits!<br /><p></p><img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=884ea228-40cd-43c7-8620-9ac0af497e9a" /></body>
      <title>Quick Update - Microsoft WebMatrix Beta released</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,884ea228-40cd-43c7-8620-9ac0af497e9a.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/07/06/QuickUpdateMicrosoftWebMatrixBetaReleased.aspx</link>
      <pubDate>Tue, 06 Jul 2010 19:54:44 GMT</pubDate>
      <description>Scott Guthrie just announced the first beta release of Microsoft WebMatrix.&amp;nbsp; I'll leave you to check out &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/06/introducing-webmatrix.aspx"&gt;his
blog post&lt;/a&gt; to find out more.&lt;br&gt;
&lt;br&gt;
This is also your &lt;b&gt;first chance&lt;/b&gt; to try out Razor.&amp;nbsp; We haven't released
the MVC View Engine for Razor, but WebMatrix includes ASP.Net Web Pages, a simple
page model that uses Razor syntax.&amp;nbsp; After installing WebMatrix, just create a
new site, drop a CSHTML file in it, put some code in and go!&lt;br&gt;
&lt;br&gt;
I'll post more details later, but for now, check out the post and play with the bits!&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=884ea228-40cd-43c7-8620-9ac0af497e9a" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,884ea228-40cd-43c7-8620-9ac0af497e9a.aspx</comments>
      <category>ASP.Net</category>
      <category>Razor</category>
      <category>WebMatrix</category>
    </item>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=8bfec649-9b91-4f0f-b051-555cea414720</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,8bfec649-9b91-4f0f-b051-555cea414720.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,8bfec649-9b91-4f0f-b051-555cea414720.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=8bfec649-9b91-4f0f-b051-555cea414720</wfw:commentRss>
      <slash:comments>14</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the first of my blog posts about the parser for the new <a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx">ASP.Net
Razor</a> syntax.  We’ve been working on this parser for a while now, and I want
to share some of how it works with my readers!
</p>
        <p>
The Razor parser is very different from the existing ASPX parser.  In fact, the
ASPX parser is implemented almost entirely with Regular Expressions, because it is
a very simple language to parse.  The Razor parser is actually separated into
three components: 1) A Markup parser which has a basic understanding of HTML syntax,
2) A Code parser which has a basic understanding of either C# or VB and 3) A central
orchestrator which understands how the two mix together.  Note that when I say
“basic understanding” I mean basic, we’re not talking about full-fledged C# and HTML
parsers here.  I’ve joked with people on the team that we should call them “Markup
Understander” or “Code Comprehender” instead :).
</p>
        <p>
So the Razor parser has three “actors”: The Core Parser, the Markup Parser and the
Code Parser.  All three work together to parse a Razor document.  Now, let’s
take a Razor file and do a full summary of the parsing procedure using these actors. 
We’ll use the sample that I used last time:
</p>
        <pre class="csharp" name="code">
&lt;ul&gt;
    @foreach(var p in Model.Products) {
    &lt;li&gt;@p.Name ($@p.Price)&lt;/li&gt;
    }
&lt;/ul&gt;
</pre>
        <p>
Ok, now we start at the top. The Razor parser is essentially in one of three states
at any time during the parsing: Parsing a Markup Document, Parsing a Markup Block
or Parsing a Code Block.  The first two are handled by the Markup Parser, and
the last is handled by the Code Parser.  So, when the Core Parser is fired up
for the first time, it calls into the Markup Parser and asks it to parse a Markup
Document and return the result.  Now the parser is in the Markup Document state. 
In this state, it simply scans forward to the next “@” character, it doesn’t care
about tags or other HTML concepts, just “@”.  When it reaches an “@”, it makes
a decision: “Is this a switch to code, or is it an email address?”  This decision
is basically done by looking just before and just after the “@” to see if they are
valid email characters.  This is the default convention, but there are escape
sequences to force it to be treated as a switch to code.
</p>
        <p>
In this case, when we see our first “@”, it is preceded by whitespace, which is not
valid in an email address.  So, we now know we are switching to code.  The
Markup Parser calls into the Code Parser and asks it to parse a Code Block. 
A Block, in terms of the Razor Parser, is basically a single chunk of Code or Markup
with a clear start and end sequence.  So, the ‘foreach’ statement here is an
example of a Code Block.  It starts at the “f” character and ends at the “}”
character.  The Code Parser knows enough about C# to know this, so it starts
parsing the code.  The Code Parser does some very simple tracking of C# statements,
so when it gets to the “&lt;li&gt;” it knows it’s at the start of a C# statement. 
“&lt;li&gt;” is not something you can put at the start of a C# statement, so the Code
Parser knows that this is the start of nested Markup Block.  So, it calls back
into the Markup Parser, to have it parse a block of HTML.  This creates a sort
of <strong>recursive ping-pong game</strong> between the Code and Markup parsers. 
We start in Markup, then call into Code, then call into Markup and so on before finally
returning back up this whole chain.  At the moment, the call stack in the parser
looks something like this:
</p>
        <ul>
          <li>
HtmlMarkupParser.ParseDocument() 
<ul><li>
CSharpCodeParser.ParseBlock() 
<ul><li>
HtmlMarkupParser.ParseBlock() 
</li></ul></li></ul></li>
        </ul>
        <p>
(Obviously, I am leaving out a lot of helper methods :)).
</p>
        <p>
This highlights a fundamental difference between ASPX and Razor.  In an ASPX
file, you can think of Code and Markup as two parallel streams.  You write some
Markup, then you jump over and write some code, then you jump back and write some
Markup, and so on.  A Razor file is like a tree.  You write some Markup,
and then put some Code <strong>inside</strong> that Markup, then put some Markup <strong>inside</strong> that
Code, and so on.
</p>
        <p>
So, we’ve just called into the Markup Parser to parse a block of Markup, this block
starts at “&lt;li&gt;” and ends at the matching “&lt;/li&gt;”.  Until that matching
“&lt;/li&gt;”, we won’t consider the Markup Block finished.  So even if you had
a “}” somewhere inside the “&lt;li&gt;” it wouldn’t terminate the “foreach”, because
we haven’t come far enough up the stack yet.
</p>
        <p>
While parsing the “&lt;li&gt;”, the Markup Parser sees more “@” characters, which
means even more calls into the Code Parser. And so the call stack grows:
</p>
        <ul>
          <li>
HtmlMarkupParser.ParseDocument() 
<ul><li>
CSharpCodeParser.ParseBlock() 
<ul><li>
HtmlMarkupParser.ParseBlock() 
<ul><li>
CSharpCodeParser.ParseBlock() 
</li></ul></li></ul></li></ul></li>
        </ul>
        <p>
I’ll go into detail on how these blocks are terminated later, because it is a little
complicated, but eventually we finish these code blocks and we’re back in the “&lt;li&gt;”
block.  Then, we see “&lt;/li&gt;” so we finish that block and pop back up to
the “foreach” block.  The “}” terminates that block, so we back up to the top
of our stack again: the Markup Document.  Then we read until the end of the file,
not finding anymore “@” characters.  And we’re done!  We’ve parsed the entire
file!
</p>
        <p>
I hope that’s made the general structure of the parsing algorithm somewhat more clear. 
The key take-away here is to avoid thinking of Code and Markup as separate streams
and think of them as constructs you nest inside each other.  Our next topic will
be Implicit Expressions, which is the logic that allows us to detect what parts of
“@p.Name ($@p.Price)” are code, and what are markup.  I’ll give you a hint, we
took some inspiration from PowerShell here ;).
</p>
        <p>
Please post any questions or comments in the comments section or email me at “andrew
AT andrewnurse DOT net”!
</p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=8bfec649-9b91-4f0f-b051-555cea414720" />
      </body>
      <title>Inside Razor &amp;ndash; Part 1 &amp;ndash; Recursive Ping-Pong</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,8bfec649-9b91-4f0f-b051-555cea414720.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/07/05/InsideRazorNdashPart1NdashRecursivePingPong.aspx</link>
      <pubDate>Mon, 05 Jul 2010 19:07:38 GMT</pubDate>
      <description>&lt;p&gt;
This is the first of my blog posts about the parser for the new &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx"&gt;ASP.Net
Razor&lt;/a&gt; syntax.&amp;nbsp; We’ve been working on this parser for a while now, and I want
to share some of how it works with my readers!
&lt;/p&gt;
&lt;p&gt;
The Razor parser is very different from the existing ASPX parser.&amp;nbsp; In fact, the
ASPX parser is implemented almost entirely with Regular Expressions, because it is
a very simple language to parse.&amp;nbsp; The Razor parser is actually separated into
three components: 1) A Markup parser which has a basic understanding of HTML syntax,
2) A Code parser which has a basic understanding of either C# or VB and 3) A central
orchestrator which understands how the two mix together.&amp;nbsp; Note that when I say
“basic understanding” I mean basic, we’re not talking about full-fledged C# and HTML
parsers here.&amp;nbsp; I’ve joked with people on the team that we should call them “Markup
Understander” or “Code Comprehender” instead :).
&lt;/p&gt;
&lt;p&gt;
So the Razor parser has three “actors”: The Core Parser, the Markup Parser and the
Code Parser.&amp;nbsp; All three work together to parse a Razor document.&amp;nbsp; Now, let’s
take a Razor file and do a full summary of the parsing procedure using these actors.&amp;nbsp;
We’ll use the sample that I used last time:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;
&amp;lt;ul&amp;gt;
    @foreach(var p in Model.Products) {
    &amp;lt;li&amp;gt;@p.Name ($@p.Price)&amp;lt;/li&amp;gt;
    }
&amp;lt;/ul&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
Ok, now we start at the top. The Razor parser is essentially in one of three states
at any time during the parsing: Parsing a Markup Document, Parsing a Markup Block
or Parsing a Code Block.&amp;nbsp; The first two are handled by the Markup Parser, and
the last is handled by the Code Parser.&amp;nbsp; So, when the Core Parser is fired up
for the first time, it calls into the Markup Parser and asks it to parse a Markup
Document and return the result.&amp;nbsp; Now the parser is in the Markup Document state.&amp;nbsp;
In this state, it simply scans forward to the next “@” character, it doesn’t care
about tags or other HTML concepts, just “@”.&amp;nbsp; When it reaches an “@”, it makes
a decision: “Is this a switch to code, or is it an email address?”&amp;nbsp; This decision
is basically done by looking just before and just after the “@” to see if they are
valid email characters.&amp;nbsp; This is the default convention, but there are escape
sequences to force it to be treated as a switch to code.
&lt;/p&gt;
&lt;p&gt;
In this case, when we see our first “@”, it is preceded by whitespace, which is not
valid in an email address.&amp;nbsp; So, we now know we are switching to code.&amp;nbsp; The
Markup Parser calls into the Code Parser and asks it to parse a Code Block.&amp;nbsp;
A Block, in terms of the Razor Parser, is basically a single chunk of Code or Markup
with a clear start and end sequence.&amp;nbsp; So, the ‘foreach’ statement here is an
example of a Code Block.&amp;nbsp; It starts at the “f” character and ends at the “}”
character.&amp;nbsp; The Code Parser knows enough about C# to know this, so it starts
parsing the code.&amp;nbsp; The Code Parser does some very simple tracking of C# statements,
so when it gets to the “&amp;lt;li&amp;gt;” it knows it’s at the start of a C# statement.&amp;nbsp;
“&amp;lt;li&amp;gt;” is not something you can put at the start of a C# statement, so the Code
Parser knows that this is the start of nested Markup Block.&amp;nbsp; So, it calls back
into the Markup Parser, to have it parse a block of HTML.&amp;nbsp; This creates a sort
of &lt;strong&gt;recursive ping-pong game&lt;/strong&gt; between the Code and Markup parsers.&amp;nbsp;
We start in Markup, then call into Code, then call into Markup and so on before finally
returning back up this whole chain.&amp;nbsp; At the moment, the call stack in the parser
looks something like this:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
HtmlMarkupParser.ParseDocument() 
&lt;ul&gt;
&lt;li&gt;
CSharpCodeParser.ParseBlock() 
&lt;ul&gt;
&lt;li&gt;
HtmlMarkupParser.ParseBlock() 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
(Obviously, I am leaving out a lot of helper methods :)).
&lt;/p&gt;
&lt;p&gt;
This highlights a fundamental difference between ASPX and Razor.&amp;nbsp; In an ASPX
file, you can think of Code and Markup as two parallel streams.&amp;nbsp; You write some
Markup, then you jump over and write some code, then you jump back and write some
Markup, and so on.&amp;nbsp; A Razor file is like a tree.&amp;nbsp; You write some Markup,
and then put some Code &lt;strong&gt;inside&lt;/strong&gt; that Markup, then put some Markup &lt;strong&gt;inside&lt;/strong&gt; that
Code, and so on.
&lt;/p&gt;
&lt;p&gt;
So, we’ve just called into the Markup Parser to parse a block of Markup, this block
starts at “&amp;lt;li&amp;gt;” and ends at the matching “&amp;lt;/li&amp;gt;”.&amp;nbsp; Until that matching
“&amp;lt;/li&amp;gt;”, we won’t consider the Markup Block finished.&amp;nbsp; So even if you had
a “}” somewhere inside the “&amp;lt;li&amp;gt;” it wouldn’t terminate the “foreach”, because
we haven’t come far enough up the stack yet.
&lt;/p&gt;
&lt;p&gt;
While parsing the “&amp;lt;li&amp;gt;”, the Markup Parser sees more “@” characters, which
means even more calls into the Code Parser. And so the call stack grows:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
HtmlMarkupParser.ParseDocument() 
&lt;ul&gt;
&lt;li&gt;
CSharpCodeParser.ParseBlock() 
&lt;ul&gt;
&lt;li&gt;
HtmlMarkupParser.ParseBlock() 
&lt;ul&gt;
&lt;li&gt;
CSharpCodeParser.ParseBlock() 
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
I’ll go into detail on how these blocks are terminated later, because it is a little
complicated, but eventually we finish these code blocks and we’re back in the “&amp;lt;li&amp;gt;”
block.&amp;nbsp; Then, we see “&amp;lt;/li&amp;gt;” so we finish that block and pop back up to
the “foreach” block.&amp;nbsp; The “}” terminates that block, so we back up to the top
of our stack again: the Markup Document.&amp;nbsp; Then we read until the end of the file,
not finding anymore “@” characters.&amp;nbsp; And we’re done!&amp;nbsp; We’ve parsed the entire
file!
&lt;/p&gt;
&lt;p&gt;
I hope that’s made the general structure of the parsing algorithm somewhat more clear.&amp;nbsp;
The key take-away here is to avoid thinking of Code and Markup as separate streams
and think of them as constructs you nest inside each other.&amp;nbsp; Our next topic will
be Implicit Expressions, which is the logic that allows us to detect what parts of
“@p.Name ($@p.Price)” are code, and what are markup.&amp;nbsp; I’ll give you a hint, we
took some inspiration from PowerShell here ;).
&lt;/p&gt;
&lt;p&gt;
Please post any questions or comments in the comments section or email me at “andrew
AT andrewnurse DOT net”!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=8bfec649-9b91-4f0f-b051-555cea414720" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,8bfec649-9b91-4f0f-b051-555cea414720.aspx</comments>
      <category>ASP.Net</category>
      <category>Razor</category>
    </item>
    <item>
      <trackback:ping>http://blog.andrewnurse.net/Trackback.aspx?guid=06dd7c2a-a7ee-461c-b191-83da14f0647b</trackback:ping>
      <pingback:server>http://blog.andrewnurse.net/pingback.aspx</pingback:server>
      <pingback:target>http://blog.andrewnurse.net/PermaLink,guid,06dd7c2a-a7ee-461c-b191-83da14f0647b.aspx</pingback:target>
      <dc:creator>Andrew Nurse</dc:creator>
      <wfw:comment>http://blog.andrewnurse.net/CommentView,guid,06dd7c2a-a7ee-461c-b191-83da14f0647b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.andrewnurse.net/SyndicationService.asmx/GetEntryCommentsRss?guid=06dd7c2a-a7ee-461c-b191-83da14f0647b</wfw:commentRss>
      <slash:comments>18</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
UPDATE: Fixed broken examples (I hope :)).
</p>
        <p>
Earlier this morning, <a href="http://weblogs.asp.net/scottgu">Scott Guthrie</a><a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx">blogged
about a new View Engine we’re developing for ASP.Net</a>.  As many of my readers
know, I joined the ASP.Net team back in October in 2009, and I’m really excited to
finally be able to share what I have been working on for the past 8 months. 
When I joined Microsoft, I was shown some early prototypes for this new syntax and
over the course of the next 8 months, we developed it into the Beta we’re going to
be releasing very soon.
</p>
        <p>
Writing the parser for Razor has essentially been my job for the last 8 months, so
I’d like to describe a little about some of the design ideas that went in to it as
well as some of the interesting ways we implemented things.  This is the first
in a few blog posts I’ll do about the Razor syntax as well as the Parser design.
</p>
        <p>
Razor syntax is designed around one primary goal: Make code and markup flow together
with as little interference from control characters as possible.  For example,
let’s take the following ASPX:
</p>
        <pre class="csharp" name="code">&lt;ul&gt;
    &lt;% foreach(var p in Model.Products) { %&gt;
    &lt;li&gt;&lt;%= p.Name %&gt; ($&lt;%= p.Price %&gt;)&lt;/li&gt;
    &lt;% } %&gt;
&lt;/ul&gt;</pre>
        <p>
Now, let's boil it down to the parts that we actually care about, removing all of
the extra ASPX control characters:
</p>
        <pre class="csharp" name="code">&lt;ul&gt;
    foreach(var p in Model.Products) {
    &lt;li&gt;p.Name ($p.Price)&lt;/li&gt;
    }
&lt;/ul&gt;</pre>
        <p>
Obviously there isn't enough data here to unambiguously determine what's code and
what's markup. When we were designing Razor, we started from here and added as little
as we could to make it absolutely clear what is code and what is markup. We wanted
Razor pages to be Code+Markup, with a little extra stuff as possible. We even used
that goal as inspiration for the file extension for C# and VB Razor pages: <strong>cshtml</strong> and <strong>vbhtml</strong>. 
</p>
        <p>
So, using the C# Razor syntax, the above example becomes:
</p>
        <pre class="csharp" name="code">&lt;ul&gt;
    @foreach(var p in Model.Products) {
    &lt;li&gt;@p.Name ($@p.Price)&lt;/li&gt;
    }
&lt;/ul&gt;</pre>
        <p>
If you ask me, that's pretty darn close to the previous example. Razor takes advantage
of a deep knowledge of C# (or VB) and HTML syntaxes to infer a lot about what you
intended to write. Let’s take this sample and break it down chunk by chunk to see
how Razor parses this document.
</p>
        <pre class="csharp" name="code">&lt;ul&gt;</pre>
        <p>
When Razor starts parsing a document anything goes until we see an "@".
So this line just gets classified as Markup and we move on to the next
</p>
        <pre class="csharp" name="code">@foreach(var p in Model.Products) {</pre>
        <p>
Here's where things get interesting. Now, Razor has found an "@". The "@"
character is the magic character in Razor. One character, not 5 “&lt;%=%&gt;”, and
we let the parser figure out the rest. If you skip ahead a bit, you’ll notice that
there's nothing that indicates the end of the block of code (like the "%&gt;"
sequence in ASPX). Rather than having it's own syntax for delimiting code blocks,
Razor tries to add as little as possible and just uses the syntax of the underlying
language to determine when the code block is finished. In this case, Razor knows that
a C# foreach statement is contained within "{" and "}" characters,
so when you reach the end of the foreach block, it will go back to markup
</p>
        <pre class="csharp" name="code">&lt;li&gt;@p.Name ($@p.Price)&lt;/li&gt;</pre>
        <p>
Now, things get even more interesting. Didn't I just say we were in Code until the
ending of the foreach? This looks a lot like Markup, and we’re still inside the foreach!
This is another case where Razor is using the syntax of the underlying language to
infer your intent. We know that after the "{" C# is expecting some kind
of statement. But, instead of a statement, we see an HTML tag "&lt;li&gt;",
so Razor infers that you intended to switch back to Markup. So we've essentially got
a stack of 3 contexts: When we started out we were in Markup, then we saw @foreach
so we went to Code, now we've see &lt;li&gt; so were back in Markup. At the closing
&lt;/li&gt; tag, we know you've finished the inner Markup block, so we go back to
the body of the foreach.
</p>
        <pre class="csharp" name="code">}</pre>
        <p>
Then we see the end of the foreach block, so we go back to the top-level Markup context.
</p>
        <pre class="csharp" name="code">&lt;/ul&gt;</pre>
        <p>
And we continue parsing markup until the next "@", or the end of the file.
You may have noticed I skipped over a bit in the middle of the &lt;li&gt; tag. I'll
save the details of that for my next post, but the essential logic is the same: "@"
starts code, and we use C# syntax to tell us when that code block is finished.
</p>
        <p>
It's great to finally be able to share the result of our hard work with everyone.
We've worked really hard to try to create a really clean syntax for mixing code and
markup and I know I’d love to hear your feedback. Post in the comments on my blog,
send me a tweet at "@anurse" or send me email at "andrew AT andrewnurse
DOT net".
</p>
        <p>
And I know you're all probably eagerly awaiting a chance to try this out. Don’t worry,
we'll have a public beta soon that you can try out!
</p>
        <img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=06dd7c2a-a7ee-461c-b191-83da14f0647b" />
      </body>
      <title>Introducing Razor &amp;ndash; A New View Engine for ASP.Net</title>
      <guid isPermaLink="false">http://blog.andrewnurse.net/PermaLink,guid,06dd7c2a-a7ee-461c-b191-83da14f0647b.aspx</guid>
      <link>http://blog.andrewnurse.net/2010/07/03/IntroducingRazorNdashANewViewEngineForASPNet.aspx</link>
      <pubDate>Sat, 03 Jul 2010 15:02:00 GMT</pubDate>
      <description>&lt;p&gt;
UPDATE: Fixed broken examples (I hope :)).
&lt;/p&gt;
&lt;p&gt;
Earlier this morning, &lt;a href="http://weblogs.asp.net/scottgu"&gt;Scott Guthrie&lt;/a&gt; &lt;a href="http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx"&gt;blogged
about a new View Engine we’re developing for ASP.Net&lt;/a&gt;.&amp;#160; As many of my readers
know, I joined the ASP.Net team back in October in 2009, and I’m really excited to
finally be able to share what I have been working on for the past 8 months.&amp;#160;
When I joined Microsoft, I was shown some early prototypes for this new syntax and
over the course of the next 8 months, we developed it into the Beta we’re going to
be releasing very soon.
&lt;/p&gt;
&lt;p&gt;
Writing the parser for Razor has essentially been my job for the last 8 months, so
I’d like to describe a little about some of the design ideas that went in to it as
well as some of the interesting ways we implemented things.&amp;#160; This is the first
in a few blog posts I’ll do about the Razor syntax as well as the Parser design.
&lt;/p&gt;
&lt;p&gt;
Razor syntax is designed around one primary goal: Make code and markup flow together
with as little interference from control characters as possible.&amp;#160; For example,
let’s take the following ASPX:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;ul&amp;gt;
    &amp;lt;% foreach(var p in Model.Products) { %&amp;gt;
    &amp;lt;li&amp;gt;&amp;lt;%= p.Name %&amp;gt; ($&amp;lt;%= p.Price %&amp;gt;)&amp;lt;/li&amp;gt;
    &amp;lt;% } %&amp;gt;
&amp;lt;/ul&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Now, let's boil it down to the parts that we actually care about, removing all of
the extra ASPX control characters:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;ul&amp;gt;
    foreach(var p in Model.Products) {
    &amp;lt;li&amp;gt;p.Name ($p.Price)&amp;lt;/li&amp;gt;
    }
&amp;lt;/ul&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Obviously there isn't enough data here to unambiguously determine what's code and
what's markup. When we were designing Razor, we started from here and added as little
as we could to make it absolutely clear what is code and what is markup. We wanted
Razor pages to be Code+Markup, with a little extra stuff as possible. We even used
that goal as inspiration for the file extension for C# and VB Razor pages: &lt;strong&gt;cshtml&lt;/strong&gt; and &lt;strong&gt;vbhtml&lt;/strong&gt;. 
&lt;/p&gt;
&lt;p&gt;
So, using the C# Razor syntax, the above example becomes:
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;ul&amp;gt;
    @foreach(var p in Model.Products) {
    &amp;lt;li&amp;gt;@p.Name ($@p.Price)&amp;lt;/li&amp;gt;
    }
&amp;lt;/ul&amp;gt;&lt;/pre&gt;
&lt;p&gt;
If you ask me, that's pretty darn close to the previous example. Razor takes advantage
of a deep knowledge of C# (or VB) and HTML syntaxes to infer a lot about what you
intended to write. Let’s take this sample and break it down chunk by chunk to see
how Razor parses this document.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;ul&amp;gt;&lt;/pre&gt;
&lt;p&gt;
When Razor starts parsing a document anything goes until we see an &amp;quot;@&amp;quot;.
So this line just gets classified as Markup and we move on to the next
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;@foreach(var p in Model.Products) {&lt;/pre&gt;
&lt;p&gt;
Here's where things get interesting. Now, Razor has found an &amp;quot;@&amp;quot;. The &amp;quot;@&amp;quot;
character is the magic character in Razor. One character, not 5 “&amp;lt;%=%&amp;gt;”, and
we let the parser figure out the rest. If you skip ahead a bit, you’ll notice that
there's nothing that indicates the end of the block of code (like the &amp;quot;%&amp;gt;&amp;quot;
sequence in ASPX). Rather than having it's own syntax for delimiting code blocks,
Razor tries to add as little as possible and just uses the syntax of the underlying
language to determine when the code block is finished. In this case, Razor knows that
a C# foreach statement is contained within &amp;quot;{&amp;quot; and &amp;quot;}&amp;quot; characters,
so when you reach the end of the foreach block, it will go back to markup
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;li&amp;gt;@p.Name ($@p.Price)&amp;lt;/li&amp;gt;&lt;/pre&gt;
&lt;p&gt;
Now, things get even more interesting. Didn't I just say we were in Code until the
ending of the foreach? This looks a lot like Markup, and we’re still inside the foreach!
This is another case where Razor is using the syntax of the underlying language to
infer your intent. We know that after the &amp;quot;{&amp;quot; C# is expecting some kind
of statement. But, instead of a statement, we see an HTML tag &amp;quot;&amp;lt;li&amp;gt;&amp;quot;,
so Razor infers that you intended to switch back to Markup. So we've essentially got
a stack of 3 contexts: When we started out we were in Markup, then we saw @foreach
so we went to Code, now we've see &amp;lt;li&amp;gt; so were back in Markup. At the closing
&amp;lt;/li&amp;gt; tag, we know you've finished the inner Markup block, so we go back to
the body of the foreach.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;}&lt;/pre&gt;
&lt;p&gt;
Then we see the end of the foreach block, so we go back to the top-level Markup context.
&lt;/p&gt;
&lt;pre class="csharp" name="code"&gt;&amp;lt;/ul&amp;gt;&lt;/pre&gt;
&lt;p&gt;
And we continue parsing markup until the next &amp;quot;@&amp;quot;, or the end of the file.
You may have noticed I skipped over a bit in the middle of the &amp;lt;li&amp;gt; tag. I'll
save the details of that for my next post, but the essential logic is the same: &amp;quot;@&amp;quot;
starts code, and we use C# syntax to tell us when that code block is finished.
&lt;/p&gt;
&lt;p&gt;
It's great to finally be able to share the result of our hard work with everyone.
We've worked really hard to try to create a really clean syntax for mixing code and
markup and I know I’d love to hear your feedback. Post in the comments on my blog,
send me a tweet at &amp;quot;@anurse&amp;quot; or send me email at &amp;quot;andrew AT andrewnurse
DOT net&amp;quot;.
&lt;/p&gt;
&lt;p&gt;
And I know you're all probably eagerly awaiting a chance to try this out. Don’t worry,
we'll have a public beta soon that you can try out!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.andrewnurse.net/aggbug.ashx?id=06dd7c2a-a7ee-461c-b191-83da14f0647b" /&gt;</description>
      <comments>http://blog.andrewnurse.net/CommentView,guid,06dd7c2a-a7ee-461c-b191-83da14f0647b.aspx</comments>
      <category>ASP.Net</category>
      <category>Microsoft</category>
      <category>Razor</category>
    </item>
  </channel>
</rss>