<?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 - Microsoft</title>
    <link>http://blog.andrewnurse.net/</link>
    <description>Oooh...pretty code</description>
    <language>en-us</language>
    <copyright>Andrew Nurse</copyright>
    <lastBuildDate>Thu, 22 Jul 2010 06:07:53 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=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=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>