April 2011

Volume 26 Number 04

ASP.NET Web Pages - Introduction to WebMatrix

By Clark Sell | April 2011

There’s no shortage of available tooling in the market for a Web developer today. In fact, chances are good that you already spend much of your day in Visual Studio. If you’ve heard of Microsoft WebMatrix, you might be wondering what it is and what its existence means to you—maybe even why you should care.

In this article I’ll explore those questions and more. I’ll start by exploring a few of the recent changes to the ASP.NET stack. Then I’ll explain how to get WebMatrix set up and create a “Hello Web” app. Then I’ll dive into some of the bells and whistles such as layout, helpers, data access, reporting and, of course, deploying. Before all that, I’ll start by defining WebMatrix.

WebMatrix is a new all-in-one Web site editor for ASP.NET Web Pages. It’s aimed at a different Web developer and a different part of ASP.NET than is usual for a Microsoft product. WebMatrix isn’t a competitor to Visual Studio; it’s more of a complement, with some overlap between the two.

You’ll find installing WebMatrix to be quick and painless. That’s because the entire package and its dependencies are less than 50MB. The package includes a text editor, Web server, database engine and the underlying framework—basically everything you need to create a Web site and deploy it. What might surprise you is that it’s not just limited to ASP.NET. WebMatrix also supports PHP and MySQL. This article will specifically focus on the .NET features of WebMatrix.

The New ASP.NET Stack

Over the past few years, the ASP.NET stack has gone through a bit of a transformation. In April 2009, ASP.NET MVC was released as a new option for Web application development in ASP.NET. The MVC, or Model-View-Controller, pattern was nothing new, but its implementation on top of ASP.NET was. Furthermore, Web Forms and MVC can both coexist in the same site in perfect harmony.

To properly enable its introduction into ASP.NET, there was some gentle framework refactoring going on so that those LEGO pieces could easily snap together how you chose. Fast forward to now, and Microsoft has just released ASP.NET MVC 3 and WebMatrix. These represent major releases that include a number of new additions and enhancements. There are three notable new additions to the framework: the Razor Parser and View Engine, or Razor for short; ASP.NET Web Pages; and IIS Express. Figure 1 depicts the relationships between all of the associated ASP.NET framework pieces.

image: The Web Stack

Figure 1 The Web Stack

In Figure 1, you might have noticed that Razor, IIS Express, SQL Compact and Web Deploy are valid options for other areas in ASP.NET Web development. Furthermore, with the release of ASP.NET MVC 3, Razor is now the default view engine. I’ll cover Razor in more detail later.

Conversely, ASP.NET Web Pages is being introduced as a peer to Web Forms and MVC. The Web Page model is a page-centric execution model, similar to PHP. Markup and code are both contained in the page itself, with helpers being leveraged to keep the code succinct. You write these pages in Razor in either Visual Basic or C#.

Getting Started

Getting started with WebMatrix is easy. The installation is delivered courtesy of the Microsoft Web Platform Installer version 3.0, or WebPI for short. It’s a client-side program that makes things such as installing SQL Express or ASP.NET MVC a breeze. For more information about WebPI, visit microsoft.com/web/downloads/platform.aspx. To quickly install it, visit http://www.microsoft.com/web/webmatrix/ and click the Download Now button. That will not only install WebPI but will install WebMatrix as well. Once the installation completes, you’ll have the following installed:

  • Microsoft WebMatrix (editor)
  • ASP.NET Web Pages with Razor Syntax (engine and framework)
  • SQL Compact (database)
  • IIS Express (development Web server)

I mentioned earlier that WebMatrix also supports PHP development. While the package supports development out of the box, you’ll need to install the PHP runtime if you’re going to create a PHP site from scratch.

Hello World Web

Just about every technical book out there has the classic “Hello World” example, so let’s create a “Hello Web” site with WebMatrix. When you open WebMatrix for the first time, you’ll be presented with a dialog with four choices. Each of these choices represents a different starting point:

  • My Sites
  • Site From Folder
  • Site From Template
  • Site From Web Gallery

My Sites simply includes the past sites you’ve been working on. Site From Folder will open any folder as the root of a site. Anything that’s listed in that folder will show up as part of the assets of the site. You can also right-click on a folder and select Open as a Web Site with Microsoft WebMatrix, which behaves the same as the Site From Folder.

WebMatrix ships with a number of prebuilt Web templates to jumpstart your site creation. Selecting Site From Template will set up your folder structure with all of the source code needed to have a site based on that template. At the time of this writing, there were five templates: Empty Site, Starter Site, Bakery, Photo Gallery and Calendar. More will be available in the future.

Site From Gallery might be the most interesting. For a number of years now, you could use WebPI and download applications such as Umbraco or WordPress, customize them at will and deploy to your hosting provider. Unfortunately there really wasn’t an integrated end-to-end story. Now, from within WebMatrix, you can actually start development from an existing application such as Umbraco. WebMatrix and WebPI will set up everything needed to start your site from one of the applications listed in the gallery. Once WebMatrix sets things up, you can customize as needed and use the deployment capabilities of WebMatrix to deploy to your hosting provider.

To create our Hello Web demo, let’s start by opening WebMatrix and selecting Start from Template. Select the Empty Site template and give the site a name—HelloWeb in this case. WebMatrix will create an empty folder with the name you chose. Now Select the Files tab and then Add a file to your site from that main window. The first thing you should notice is the new file extension. ASP.NET WebPages has two new file formats: CSHTML and VBHTML. The first two letters of the extension indicate the language that the Razor parser should use to parse code: C# and Visual Basic, respectively. I’ll select a CSHTML file and name it HelloWeb.cshtml. That will automatically open that file prepopulated with some default HTML.

Adding the text Hello Webto the existing body element will finish Hello Web. WebMatrix will automatically detect all of the Web browsers you have installed. You can run your site in any or all of them with a simple button click. Clicking Run in the ribbon will start the default browser and open and render the page you had focus on. Of course, in the case of Hello Web, you’ll see the words “Hello Web.”

Coding in Razor

As I stated earlier, Razor is a code and markup templating engine. What that really means is that you write some syntax that’s later interpreted and sent to the requestor. Here’s the HTML for our simple Web page, with a little code calling @DateTime.Now:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
     <title>Hello World</title>
  </head>
  <body>
    Hello Web it's @DateTime.Now
  </body>
</html>

That code makes a call to the Now method of the .NET System.DateTime class. The result is a page that would render what you see in Figure 2.

image: Hello Web in the Browser

Figure 2 Hello Web in the Browser

We can get a bit more complicated, too. Let’s create some properties, run a loop, intermix some HTML and just mix it all together for fun. Figure 3 is just that, with some valid HTML omitted for brevity. And Figure 4 shows the rendered results.

Figure 3 CodingRazor.cshtml

@{
  var cars = new string [] { "Camaro", "Avalanche", "Honda"};
  var emailAddress = "cars@something.com";
}
 
<ul>
  @foreach ( var car in cars ) {
    <li>
      <a href="http://@(@car).something.com">@car</a>
            
      @if ( car == "Camaro" ) {
        @: Is my favorite!  
        }
    </li>
  }
</ul>

To comment on this list of cars e-mail us at @emailAddress.

image: The Cars Code Rendered in a Browser

Figure 4 The Cars Code Rendered in a Browser

Let’s take a closer look at some of that code listed in Figure 3. Start with the hyperlink “http://@(@car).something.com.” You see “@(@car).” There I need to explicitly tell Razor that @car is the variable, because it’s embedded within the URL. The next code nugget is the content block defined by “@:”. Within the loop, there’s an If statement containing the text content “Is my favorite!”. If you remove “@:”, Razor wouldn’t compile because that text content isn’t wrapped in HTML. Finally, at the end, we call @emailAddress, but end the sentence with a period. Razor was smart enough to know @emailAddress was a variable and not a class. The coolness doesn’t end there. By viewing the source on that page, you’ll see that pure HTML was rendered to the browser, as shown here:

<ul>
  <li><a href="http://Camaro.something.com">Camaro</a> Is my favorite! </li>
  <li><a href="http://Avalanche.something.com">Avalanche</a> </li>
  <li><a href="http://Honda.something.com">Honda</a> </li>
</ul>

To comment on this list of cars e-mail us at cars@something.com

Layout

Razor introduces a new way to structure your site content in a reusable way. If you’re familiar with the Master Pages idiom in ASP.NET Web Forms, Razor uses layout to accomplish the same thing, but with a different approach. As a tangential observation, it’s important to note the two layout approaches don’t work together, meaning Master Pages can’t be used as a layout engine for Razor, and vice versa.

To start with layout, I’m going to create a page that begins with an underscore; for example, _MasterLayout.cshtml. Underscored pages can’t be rendered directly in the browser and must be referenced by other, public pages. In a way, an underscored page is like a class in an assembly marked internal. In that page, I’ll structure how and where different pieces of the page will get inserted by downstream references. There are three main classes you use to help structure things: RenderSection, RenderPage and RenderBody. Figure 5 shows a simple master layout page using all three.

Figure 5 The RenderSection, RenderPage and RenderBody Classes

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title></title>
    @RenderSection("ClientScripts", required: false)
  </head>
  <body>
    @RenderPage("~/layout/shared/_header.cshtml")
    @RenderBody()
    @RenderPage("~/layout/shared/_footer.cshtml")
  </body>
</html>

This master page will need to be referenced by any child page that wants to inherit its defined layout. As seen here, the first line does exactly that:

@{ Layout = "~/layout/shared/_MasterLayout.cshtml"; }
    
@section ClientScripts {
  Custom Script Here </br>
}
 
Some body content

In my layout page, I defined an optional section (@RenderSection) in the head section of our page. Because it was optional, a child page has the option to implement it if it so chooses. To implement a section, use the “@section*” followed by the name you specified in the “@RenderSection*” call. The remainder of the page (in this example) is assumed to be the content. This will be consumed by the “*@RenderBody.*” See the online source code accompanying this article for a more detailed example.

Running default.cshtml (in the folder named “layout” in the source code download) will produce the output shown in Figure 6. All sections were rendered correctly and emitted as pure HTML to the browser.

Figure 6 Output from Running default.cshtml

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title></title>
  Custom Script Here </br>
</head>
<body>
  <p>this was rendered from ~/layout/shared/_header.cshtml</p>
  Some body content
  <p>this was rendered from ~/layout/shared/_footer.cshtml</p>
</body>
</html>

Help Me Help You

You hear it all the time in the software industry: reuse. WebMatrix introduces a concept similar to the plug-in model used in WordPress or jQuery. In WebMatrix, these plug-ins are known as helpers. The concept is similar: they’re published packages of reusable functionality, or little nuggets of .NET code that are purposely built and packaged for easy distribution and consumption. The helper package itself is merely a NuGet package (see nuget.codeplex.com). If you’re a .NET developer building and using helpers, it will feel no different than consuming any standard .NET class, because that’s all it really is.

Helpers are stored and retrieved from a cloud-based NuGet feed. So how do you find these elusive helpers? After you’ve opened up your site in WebMatrix, click Run. That opens your site in the browser, for example: http://localhost:53655/default.cshtml. Then browse to http://localhost:53655/_admin. This is the only underscored page that will render, and that’s just on your local machine. At this point, you’ll be prompted to create a password, after which you’ll be taken to the Package Manager (see Figure 7).

image: ASP.NET Web Pages Administration Package Manager

Figure 7 ASP.NET Web Pages Administration Package Manager

You can view helpers in one of three categories: Installed, Online and Updates. You can also view by the source from which they originated. That source is a NuGet feed. The default feed is the official directory of WebMatrix helpers, but you could add other sources as well.

Now that we have the list of packages, let’s install one. For demonstration purposes, let’s install and explore a helper called the Url Shortener Helper (see UrlShortenerHelper.CodePlex.com). This is a helper I built to aid in shortening URLs, leveraging a provider such as bit.ly. The concept is simple: Take a URL and shorten it, hiding the interaction with the provider chosen to accomplish it. Now let’s switch to Online and select Install for the UrlShortener. This will download, install and configure the helper into your site.

Helpers are currently written in two ways—either directly in Razor or in a compiled assembly. Which should you choose? It depends, of course. In the case of my Url Shortener, the code is really just an interaction with an external provider API; it doesn’t emit any HTML. So in my scenario, the helper was better suited to be packaged in an assembly. The Facebook helper, on the other hand, emits a large amount of markup and, as such, is written as a CSHTML helper. For helpers that need to wrap API calls and emit markup, there’s also a hybrid approach in which you could do both—have some functionality in Razor and in an assembly.

You’ll find an example of this in the UserVoiceHelper at UserVoiceHelper.codeplex.com.

Looking back at our site, you now see a few new assets. Under the root of your site, there’s now a /bin folder with two new assemblies. This happened as a result of NuGet installing our package. There will also be a ReadMe.UrlShortener.txt file in the root with instructions on how to use the helper. Other helpers, such as the Facebook helper, will actually add their own folders and code to the App_Code folder.

Data

It’s pretty hard to have a Web site without having a data store behind it. WebMatrix ships with a new version of SQL Compact Server Compact Edition 4, or SQL Compact. It’s a free embedded database engine that supports no installation and xcopy deployments. Because SQL Compact is a version of SQL Server itself, you can always upgrade to more advanced versions of SQL Server with little work. WebMatrix even ships with a tool that will help you upgrade your SQL Compact database to SQL Server.

WebMatrix has built-in editor support for your database needs. From table creation to data creation, you can do it all from the comfy confines of WebMatrix. Once you’ve created your database and all of the necessary assets, it will all be contained in a database file with an SDF extension. Figure 8 is a simple data-access call. 

Figure 8 Cars.cshtml Querying for Data

@{ 
  var db = Database.Open("Cars");
  var selectQueryString = "SELECT * FROM Models ORDER BY Year";
}
<!DOCTYPE html>
<html lang="en">
  ... 
    <tbody>
      @foreach (var row in db.Query(selectQueryString))
      {
        <tr>
          <td>@row.Year</td>
          <td>@row.Maker</td>
          <td>@row.Model</td>
        </tr>
      }
    </tbody>
  ...
</html>

I start by opening the cars database and later query that connection in a foreach loop. In the loop, I display a result per row. After you render the page, send the page to source view and you’ll again find pure HTML. Parts of this example were omitted for brevity but are available in the online source code in a file named DataAccess.cshtml.

Serving It Up

Your Web site is basically useless if you don’t have something to serve it up. On the Windows platform, that has always meant IIS. For more information on IIS, visit iis.net. IIS has historically been a feature of the Windows OS and something that your hosting provider or IT professionals would configure and use. Web developers on Windows typically used IIS or the built-in Visual Studio Web server, called Cassini. With the release of WebMatrix and Visual Studio 2010 SP1, we now have IIS Express as an additional option. IIS Express is the best of both worlds—the power of IIS and the simplicity of Cassini.

IIS Express installs with WebMatrix by default, but you can download it separately with WebPI. Unlike the full version of IIS, IIS Express is installed just like any other user-mode program. You’ll find it at C:\Program Files (x86)\IIS Express. It’s comprised of two programs, iisexpress.exe and iisexpresstray.exe. The former is really IIS Express, and iisexpresstray is the visual tray that runs in the Windows system notification area.

Starting up IIS Express is typically done in the command line (cmd.exe). There are a number of options you can pass in such as path, port, name, framework version and more. For all of the commands, type: > iisexpress.exe /? If I wanted to start up a Web server for my new WebMatrix site, outside of WebMatrix itself, I would just need to type the following:

> iisexpress.exe /path:"c:\MySite" /port:81

 Then you could open your favorite Internet browser and browse to http://localhost:81, which would serve up your site located at C:\MySite.

WebMatrix hides all of this from you, but that power is there if you want it. Upon clicking Run, WebMatrix will start up IIS Express in the system tray and configure it all on your behalf. When you shut down WebMatrix, IIS Express is shut down as well.

Search Relevance

Search relevance is more important now than ever. You can’t just wait for Bing or Google to make you relevant. To aid you in your relevance quest, WebMatrix has a reporting feature called Search Engine Optimization (SEO).

Clicking on the reporting tab down in the lower-left-hand corner of WebMatrix will present you with the ability to create a new SEO Report. In doing so, WebMatrix crawls your site and looks for those potential areas where your site could be more relevant to search engines. Once WebMatrix has finished crawling your site, it will give you a detailed list of your violations as well as recommendations on how to resolve them. See Figure 9 for a sample SEO Report that was run with the demo code for this article.

image: SEO Reporting

Figure 9 SEO Reporting

Deploying

You’ve spent countless hours perfecting your site. Now it’s time to deploy it. WebMatrix does that in just two steps: configure and deploy. In the WebMatrix ribbon, you’ll find a Publish button. Configuring your deployment settings is of course dependent on your hosting provider and what it has enabled. Figure 10 shows the publish settings dialog. Out of the box, WebMatrix supports both FTP and WebDeploy. Enter your appropriate settings and click Publish.

image: Publishing Settings

Figure 10 Publishing Settings

Don’t have a hosting provider? Click Find Hosting Provider. That will take you to asp.net/webmatrix/hosts, where you can choose a hosting provider that’s already configured and certified to work with WebMatrix. If you already had a site, WebMatrix has that covered, too. In that same Publish menu, you’ll find Download Published Site. It’s simply the reverse of deploying. It works off the same settings you configured to deploy. Once you’ve configured your publish settings, you can then download your current site locally to edit. When your edits are done, just redeploy.

Growing Up

When choosing a framework, wouldn’t it be nice to know if it could scale with you as your needs and complexity increase? Over the years, ASP.NET has been building the LEGO pieces to do exactly that. Today we have an entire bucket full and we can snap them together as our needs demand it. In Figure 1 you saw how everything is built on top of ASP.NET and, furthermore, .NET. This means that taking your WebMatrix application and migrating it to Visual Studio is in fact possible. It’s a click of a button.

Looking closer at the WebMatrix ribbon will reveal a button to open in Visual Studio located at the top-right-hand corner. This will open your site as an ASP.NET Web Site project in Visual Studio. But it doesn’t stop at the core Web site. Chances are that you have a database, too. You can port any SQL Compact database to higher levels of SQL Server. WebMatrix will also aid you in this migration process by using the Migration button in the database menus.

Summing up, WebMatrix is designed to be a tool for everyone, and it complements Visual Studio well. How you leverage WebMatrix will depend on the task at hand, but nonetheless it’s a tool in your toolbox. It’s seamless to pick and choose what ASP.NET pieces you might leverage, and it makes migrating to Visual Studio and SQL Server seamless, too. The advent of helpers and the new layout subsystem have made reuse become a reality. If creating a site from scratch wasn’t appealing, with WebMatrix you can start from a proven application listed in WebPI such as Umbraco or WordPress and deploy right to your hosting provider.

Unfortunately, there are many more features I couldn’t cover in this article, including caching, routing and debugging. You can find all of the links used in this article at bit.ly/IntroToWebMatrix.


Clark Sell works as a senior developer evangelist for Microsoft outside of Chicago. He blogs at csell.net, podcasts at DeveloperSmackdown.com and you can follow him on twitter.com/csell5.

Thanks to the following technical experts for reviewing this article: Erik Porter,Mark Nichols and Brandon Satrom