Using”using” keyword in webmatrix

On July 6, “His Highness Gu” – well wondering who is this – none other than Scott Guthrie of Microsoft. I like to address him as “His Highness Gu” after going through Scott Hanselmans’ (Principal Program Manager, MS) this video. So on July 6 Scott blogged about a new tool that was released which is known as “WebMatrix”. WebMatrix is a lightweight web development tool that integrates 3 new web development technology such as:

So i too jumped into the band wagon of users who started to check out the new tool. Must say its so light weight but keeps you the full power to build great looking sites in just couple of hours. Not only that it has some cool starter example sites – namely – Bakery, Photo album etc. These examples have all the code you need to just copy & paste and finish up a site.

Now, as they say – “Necessity is the mother of invention” – i am going to talk about an aspect till now nobody has blogged about (as far as i know). I started to play around with WebMatrix by creating a site of my own. No this was not a example site – rather – i am trying to build something for the community. Will spill more beans may be in one of the coming blogs. So in the course of building this site i started looking at different aspects of the WebMatrix. I was working on user creation module and as any user registration has, i too have an email field. As i said there is a example site bundled with WebMatrix known as “StarterSite” which by the way is an excellent code example of a full fledged site with security around it. So i too looked at that example. In the registration page processing – the code was checking only if the email field was empty or not. If empty it was not valid. Check the code below:

   1:   // Validate the user's email address
   2:          if (email.IsEmpty()) 
   3:          {
   4:              emailErrorMessage = "You must specify an email address.";
   5:              isValid = false;
   6:          }

As you can see there is no check for the valid format. So this is where i started to see how can i add my code to check for the valid format. The first thing that comes to any developer with a decades experience in the field is how about a regular expression. True isn't it. So next question was how do i use regex in WebMatrix. Again i Google/Binged about the keywords “WebMatrix and Regular Expressions” to see if anybody else has had the same thoughts as of me. But didn't get the required search results. So i started to play around with  the code.

As the WebMatrix documentation says, Razor is just a view engine for the ASP.NET web page development. So i can reap any .NET based feature from WebMatrix too. WebMatrix is just giving a new way of coding an ASP.NET web page using a new view engine code named Razor. If you are wondering why the name Razor – i think its my analogy to say that – with this new templating format and engine the syntax to code a mark up and server side code is extremely fast. So we all know that Razor are known to be sharp and perform their work faster. Its just my thought.

Coming to the code, what i was thinking here was – i am already in .NET, coding a server side piece of code block. So shouldn't it support any C# object. Well a noble thought. So spun up a little piece of code to see if i was right. I had  the following piece of code added in the page now. I just tried to instantiate a Regular Expression object as below:

   1:  // Validate the user's email address
   2:          if (email.IsEmpty()) {
   3:              emailErrorMessage = "You must specify an email address.";
   4:              isValid = false;
   5:          }
   6:          var pattern = “<pattern>”;
   7:          var regEx = new Regex(pattern);

For those of you wondering how a Razor file looks like – here is the screen shot of the Register.cshtml. By the way CSHTML is the new file extension to let the framework know that it has to use Razor templating engine for parsing:

Now here is the output of the above page:

Well what can i say – its our very own familiar Yellow Screen Of Death. So what happened. If you look at the error message – it is saying me that it cannot find the object Regex and asking me if i have missed to put any references by putting “USING” directive. Now this is really something i didn’t expect – “are you missing a using directive”. If you notice the Register.cshtml file above – in Razor so far all the examples i have seen – nobody has shown a code piece using the “USING” directive. Well then i am might be the first one to dig this out. Another interesting thing i noticed was – look at the bottom of the page. It has 2 sections – “Show Detailed Compiler Output” and “Show Complete Compilation Source”. What – show complete compilation source – Eureka Eureka – only that i was not in a bath tub but on a chair : ). That's what i want to know – what did the compiler compile my page as. Great. So here is what the compilation source of my Register.cshtml looked like:

Line 2:    //------------------------------------------------------------------------------
Line 3:    // <auto-generated>
Line 4:    //     This code was generated by a tool.
Line 5:    //     Runtime Version:4.0.30319.1
Line 6:    //
Line 7:    //     Changes to this file may cause incorrect behavior and will be lost if
Line 8:    //     the code is regenerated.
Line 9:    // </auto-generated>
Line 10:   //------------------------------------------------------------------------------
Line 11:   
Line 12:   namespace ASP {
Line 13:       using System;
Line 14:       using System.Collections.Generic;
Line 15:       using System.IO;
Line 16:       using System.Linq;
Line 17:       using System.Net;
Line 18:       using System.Web;
Line 19:       using System.Web.Mvc;
Line 20:       using System.Web.Mvc.Html;
Line 21:       using System.Web.Security;
Line 22:       using System.Web.UI;
Line 23:       using Microsoft.Data;
Line 24:       using Microsoft.WebPages;
Line 25:       using Microsoft.WebPages.Helpers;
Line 26:       using System.Configuration.Provider;
Line 27:       
Line 28:       
Line 29:       public class Register_cshtml : Microsoft.WebPages.WebPage {
Line 30:           
Line 31:       protected Microsoft.WebPages.WebPageHttpApplication 
               ApplicationInstance {
Line 32:               get {
Line 33:                   return ((Microsoft.WebPages.WebPageHttpApplication)
Line 34:               }
Line 35:           }
Line 36:           
Line 37:           public override void Execute() {
Line 38:               
Line 39:               #line 1 "C:\Users\kashyapa\Documents\My Web Sites\Starter Site\Account\Register.cshtml"
Line 40:   
Line 41:       // Set the layout page and page title
Line 42:       LayoutPage = "~/_SiteLayout.cshtml";
Line 43:       PageData["Title"] = "Register an Account";
Line 44:   
Line 45:       // Initialize general page variables
Line 46:       var email = "";
Line 47:       var password = "";
Line 48:       var confirmPassword = "";
Line 49:       
Line 50:       // Validation
Line 51:       var isValid = true;
Line 52:       var emailErrorMessage = "";
Line 53:       var passwordErrorMessage = "";
Line 54:       var confirmPasswordMessage = "";
Line 55:       var accountCreationErrorMessage = "";
Line 56:       // var captchaMessage = "";
Line 57:   
Line 58:       // If this is a POST request, validate and process data
Line 59:       if (IsPost) {
Line 60:           email = Request.Form["email"];
Line 61:           password = Request.Form["password"];
Line 62:           confirmPassword = Request.Form["confirmPassword"];
Line 63:           
Line 64:           // Validate the user's captcha answer
Line 65:           // if (!ReCaptcha.Validate("PRIVATE_KEY")) {
Line 66:           //     captchaMessage = "Captcha response was not correct";
Line 67:           //     isValid = false;
Line 68:           // }
Line 69:           
Line 70:           // Validate the user's email address
Line 71:           if (email.IsEmpty()) {
Line 72:               emailErrorMessage = "You must specify an email address.";
Line 73:               isValid = false;
Line 74:           }
Line 75:           var pattern = “<pattern>”;
Line 76:           var regEx = new Regex(pattern);     

As you can see this is nothing new. Same as what you would expect in ASP.NET page. Now coming back to my problem – why isn't Regex recognised as object. Because – take a close look at the using directive sections. There is no “System.Text.RegularExpressions” namespace added. So compiler promptly told me hey i can’t find the object. So far so good. Now all i have to figure out is how do i add a using statement inside a Razor  template. What i did was i added using as below:

      using System.Text.RegularExpressions;        
     // Set the layout page and page title    
    LayoutPage = "~/_SiteLayout.cshtml";    
    PageData["Title"] = "Register an Account";

Notice that i have added the using statement at the top of the page. I am expecting this is gonna work. Lets see what happened when i ran in the browser:


Oops – again a Yellow Screen of Death. But this time – with loads of information. What it told me was :

Namespace imports and type aliases cannot be placed within code blocks.  
They must immediately follow a '@' within markup.
It is recommended that you put them at the top of your page,
as in the example below:
@using System.Drawing;
   // Now you can use types from System.Drawing throughout your page

Boom there you go. Thanks Microsoft. Without any documentation i was able to figure out what’s the usage with just the error messages. Great debugging i must say. Just kidding. So all you need to do is place the using statements as the first lines of code which should be immediately followed by “@” sign. So i modified the code as below:

@using System.Text.RegularExpressions;
    // Set the layout page and page title
    LayoutPage = "~/_SiteLayout.cshtml";
    PageData["Title"] = "Register an Account";
    var pattern = "<pattern>";
    var regExp = new Regex(pattern);


As soon as modified with code with above statements – i got the page rendered without any problem.

As you can see every problem has a solution one way or the other. I just wanted to share my experience here. So created this blog post.


Using directive can be used in the Razor template files. They need to be the first statements to be placed in the file and should be immediately followed by “@” symbol. This gives me a lot of exploration points.

Line of thought:

I am not sure if the “Show Complete Compilation Source” link will be present even in the production environment whenever a yellow screen of death comes up. I am running the WebMatrix beta which comes with SQL CE and IIS Express. What’s good about this feature is that i can know what the compiler did. But at the same time if this is the behavior even in the production environment then this is gonna expose all the “MAGIC STRINGS” that we developers do use in our codes all the times and some of them may be sensitive information. I am not the best person to comment on this. May be if “His Highness Gu” has time to go through my article, only he can anser this.

As always, till next Happy Coding. Code with passion.


Technorati Tags: Tags:

No Comments