Welcome to the WebMatrix - Introducing Microsoft's new Web Stack

Ever since Microsoft released ASP.NET in 2002, web developers have been able to use a powerful platform to build a wide range of web applications and services. But this power comes at a price. Getting started with ASP.NET takes quite some time and effort. Before you can run your first Hello World page, you need to download and install a lot of software, taking up quite a bit of time and bandwidth. You need Visual Web Developer (Express), you need SQL Server (Express or any other version) and you may need IIS if you want to test out more realistic scenarios, some of which require special privileges for the account you use on your machine. Once you have all the tools, the real work begins. My latest book, Beginning ASP.NET 4 in C# and VB needed 803 pages to take you from a developer newbie to a competent ASP.NET web developer.

In other words, you're facing quite some hurdles when you want to start developing web applications on the Microsoft platform, especially if you're a hobbyist web developer.

To make the Microsoft stack more appealing to beginning web developers, Microsoft is introducing WebMatrix.

Introduction

If you've been around in the ASP.NET world for some time, this name may sound familiar. Yes, WebMatrix was also the name of the free tool to develop ASP.NET web applications with on .NET 1. However, with the introduction of the free Visual Web Developer Express editions, WebMatrix became pretty much obsolete. Now the name is back, but with a different meaning. WebMatrix is "a stack of products that together enable you to rapidly develop and deploy web applications". Figure 1 shows the WebMatrix stack:

The WebMatrix Stack
Figure 1

At the bottom of the stack you see IIS Express, which is a light-weight version of the real IIS used for local development. Scott Guthrie recently announced and introduced IIS Express on his blog. IIS Express removes the issues typically associated with the production version of IIS on your development machine, such as security and deployment.

The Framework part of the stack consists of the .NET Framework version 4 with a simplified scripting language and a compiler and a simple API with helper methods on top.

The Database used in WebMatrix is SQL Server Compact which is X-Copy deployable making it easy to deploy to a host that doesn't have SQL Server installed.

Finally, you use the tool to develop the actual application. It's a light-weight web editor and web site management tool and has features to create new sites (from scratch or from existing templates; more on that later), create new pages, configure your site (by configuring the underlying IIS Express configuration files), view requests, manage your database and its data, run Search Engine Optimization reports against your site and more.

A number of aspects of WebMatrix make it easy to get started with it. First of all, it should be easy to install using the Web Platform Installer (WPI) version 3. You should be able to run WPI, hit "Get started" and be done in minutes. The total download size should be around 50 MB max; and may be even less if you already have some components installed. Another great feature is the "Learn WebMatrix" documentation that ships with the product. When you download and install WebMatrix you also get access to an eBook consisting of 15 chapters and two appendices, dealing with topics such as the following:

  • Getting started with WebMatrix
  • Introduction to ASP.NET web programming using the Razor syntax
  • Creating a consistent look using layouts
  • Working with forms
  • Working with data
  • Working with files, images, video and e-mail
  • Integrating your site with social networks and web sites
  • How to analyze traffic
  • Using the built-in security services
  • Advanced topics such as caching and debugging

This documentation should get you up and running with WebMatrix in no-time.

To see how to use Webmatrix, the following guide you through the process of creating a new site in WebMatrix. Later sections dig deeper in to the Razor syntax and other features that ship with WebMatrix.

When you start up WebMatrix, you're greeted by the Quick Start screen:


Figure 2 (click to enlarge)

Here you can choose to create a new site from a number of sources: the on-line gallery, from a local template or from an existing folder. Additionally, you can open web sites you created earlier using My Sites. The on-line gallery enables you to choose among a wide variety of existing templates for various purposes such as eCommerce, Content Management Systems, Blogs and more as you can see in Figure 3:


Figure 3 (click to enlarge)

If you choose Site From Template you can choose among a number of ready-made templates, including an empty site, a starter site, a photo gallery and a Bakery site (for all you bakers out there). The empty web site is indeed empty so I am choosing the Starter Site to have something to work with. You see the screen shown in Figure 4 appear:


Figure 4 (click to enlarge)

The first thing you'll notice is that WebMatrix uses the familiar Office Ribbon interface. On the ribbon you see a bunch of buttons that enable you to run and publish your site, start and stop IIS Express and look at the requests made to this web site.

On the Accordion bar on the left you see the same Requests item and a Settings item that lets you configure IIS Express settings such as Default Documents, whether or not to use SSL and the target .NET framework used for the site.

At the bottom of the accordion, you see items for the Site (which enables the Requests and Settings options shown in Figure 4), the files that make up your site, any databases your site may have and a Reports options which lets you run Search Engine Optimization analytics on your web site.

If you click Files, you see the pages that make up your site, as shown in Figure 5:


Figure 5 (click to enlarge)

By convention, files that start with an underscore cannot be requested by the user directly. In this case, there are two such files. The file _start.cshtml contains database and e-mail configuration and is included automatically in order to set up a database connection.

The file _SiteLayout.cshtml is what is called a Layout Page and serves as the layout definition for pages in your site. Think "Master Page" if you're familiar with ASP.NET Web Forms or MVC. The .cshtml extension is what makes this a C# WebMatrix file; for VB you would use .vbhtml instead.

The Layout Page contains a mix of standard markup and Razor syntax (more on that later). For example, the main content section of the page looks like this:

<div id="main">
  <h2>@PageData["Title"]</h2>
  @RenderBody()
  <p />
  <div id="footer">
    &copy;@DateTime.Now.Year - My ASP.NET Web Page
  </div>
</div>

Notice how it uses @PageData to display the title set by a Content Page that uses this Layout Page. Additionally, it uses embedded code expressions using .NET's DateTime.Now.Year. The property is prefixed with an @ symbol which turns it into a code expression, resulting in the current year being displayed in the page.

To make use of this Layout Page, a Content Page needs to set the Layout property. Additionally, it could assign a value to the PageData for the page's title. Here's the content of the complete Default.cshtml page that makes use of this Layout Page:

@{ 
  LayoutPage = "~/_SiteLayout.cshtml";
  PageData["Title"] = "Welcome to my Web Site!";
}
<p>
  ASP.NET Web Pages make it easy to build powerful .NET based applications for the web.
</p>

At the top, in a code block that starts with an @ symbol, both the LayoutPage and the page title are set. The remainder of the content is then considered the body of the page and is rendered at the location where the Layout Page calls RenderBody() as shown previously. When requested by the browser, the Layout Page and the Content Page are merged and sent to the browser.

You're not limited to a single body section though. You can create what are called content sections which can be rendered in the Layout Page by calling RenderSection. For example, if you add the following to the Content Page:

@section MainMenu {
  <ul>
    <li>Home</li>
    <li>About</li>
  </ul>
}


you can render that section in the Layout Page with this code:

@RenderSection("MainMenu")

The net result of this is that the content you defined in the Content Page (the <ul>) is displayed at the location in the Layout Page where you called RenderSection("MainMenu"). You can have as many sections in your Content Pages as you want, and all layout that's not part of a section (e.g. not wrapped in a code block that starts with @section) or a code block is considered to be part of the (implicit) body section.

Programming Using Razor Syntax

You may have noticed some odd syntax in these examples. The code used for these pages is a mix of plain text, client side markup and what is called the Razor Syntax, a "new and simplified programming syntax for writing ASP.NET server code". The documentation that ships with WebMatrix has extensive coverage of this new syntax so I won't repeat all of that that here, but instead show you some of the highlights. Although the documentation that ships with WebMatrix is in C#, the syntax supports both C# as well as VB. The appendix that is part of the documentation shows you how to work with VB.

Chapter 2 - "Introduction to ASP.NET Web Programming Using the Razor Syntax" lists the following 8 "Programming Tips" for Razor:

1. You add code to a page using the @ character

The @ character starts inline expressions, single statement blocks, and multi-statement blocks. For example, @section shown earlier defines a multi line block, while the current year is an example of an in-line expression.

2. You enclose code blocks in braces

A code block includes one or more code statements and is enclosed in braces as shown with the code example that set the LayoutPage property in the Content Page

3. Inside a block, you end each code statement with a semicolon

Inside a code block, each complete code statement must end with a semicolon. Inline expressions do not end with a semicolon. Again, this is shown in the example that sets the LayoutPage property.

4. You use variables to store values

You can store values in a variable, including strings, numbers, and dates, etc. You create a new variable using the var keyword. You can insert variable values directly in a page using @. For example:

@{ var welcomeMessage  = "Welcome, new members!"; }
<p>@welcomeMessage</p>

outputs the message "Welcome, new members!" between a pair of <p> tags.

5. You enclose literal string values in double quotation marks

To specify a string, you enclose it in double quotation marks as shown in the previous example. To display a double quote in a string literal, you need to double it ("").

6. Code is case sensitive

Just like C#, code is case sensitive.

7. Much of your coding involves working with objects

Just as in other parts of the .NET Framework, Razor Syntax makes use of objects everywhere. To access properties of objects you use the same familiar dot syntax. For example, the following outputs the current page being requested:

@Request.Url

8. You can write conditional code that makes decisions

Just like in C#, if and else statements are supported. The following snippet shows how to display different output based on the fact if this is the first request to a page (a GET operation), or the result of a POST operation (more or less similar to Page.IsPostBack in ASP.NET) using the built-in IsPost property:

@{
  if(IsPost)
  {
    <p>This page was posted using the Submit button.</p>
  }
  else
  {
    <p>This was the first request for this page.</p>
  }
}  


Notice how you can just mix and match code and HTML (the <p> elements). This works because the text is wrapped in tags which enables Razor to see the meaning of the code: output HTML rather than try to execute it as code. If you need to output a literal, you can use <text> tags which live on the server only and serve to distinguish between literal text and programming code:

@{
  if(IsPost)
  {
    <text>This page was posted using the Submit button.</text>
  }
  else
  {
    <text>This was the first request for this page.</text>
  }
}  

The result of running this code is the same, except for the <p> tags that are not present in the final code. Note that the <text> tags are not sent to the client.

Chapter 2 of the documentation - "Introduction to ASP.NET Web Programming Using the Razor Syntax" has a lot more examples of using Razor Syntax including looping (for, foreach), arrays, and exception handling.

What Else is There?

Since WebMatrix is meant to target programmers that are new to web development, it makes sense that a lot of the regular plumbing services are readily available, including database access, working with images and video, ASP.NET membership services and a lot more. If you want know more about these topics, be sure to download the beta and read the documentation. For now, I'll briefly describe a few of the features to whet your appetite.

Data Access

Capabilities to manage your SQL Server Compact database are fully integrated in WebMatrix which makes it simple to create or change tables and alter their data. Figure 6 shows the table designer for a new Article table I created:


Figure 6 (click to enlarge)

If you're familiar with managing databases in Microsoft Access 2007 or 2010, you'll feel right at home.

Displaying data is then a two-step process: define the database connection and SQL statement, and display the data. The first step requires this code:

@{ 
  var db = Database.OpenFile("StarterSite.sdf");
  var selectQuery = "SELECT Id, Title FROM Article";
}

while displaying the data can be as simple as this:

<ul>
  @foreach (var row in db.Query(selectQuery))
  {
    <li>@row.Title</li>
  }
</ul>

Inserting, updating and deleting data works in a similar way, by executing a SQL statement using db.Execute.

Clearly, for real-world applications you need a bit more than this, but this example does show the power of the built-in capabilities, abstracting away all the complexity of creating SQL connections, commands, readers and more.

Uploading Files

Uploading files looks quite similar to the FileUpload control and the File class in .NET. You can define an upload control in the page like this:

@FileUpload.GetHtml
(
  initialNumberOfFiles:1, 
  allowMoreFilesToBeAdded:false, 
  includeFormTag:true, 
  uploadText:"Upload")
  @if (IsPost) {
    <span>File uploaded!</span><br/>
}     

To save the file, you can use code like this:

@{  
  var fileName = "";
  if (IsPost) {
    var fileSavePath = "";
    var uploadedFile = Request.Files[0];
    fileName = Path.GetFileName(uploadedFile.FileName);
    fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" + fileName);
    uploadedFile.SaveAs(fileSavePath);
  } 
}

Notice how properties such as initialNumberOfFiles and allowMoreFilesToBeAdded make it easy to change the client side behavior of the upload page. Set allowMoreFilesToBeAdded to true and the user gets an Add button to upload multiple files at once, shown in figure 7:


Figure 7 (click to enlarge)

Besides uploading files, WebMatrix also makes it easy to work with images. For example, you can scale and flip images and there is built-in support for adding watermarks, something that previously required third party controls or a fair bit of custom code.

Sending E-mail

Sending e-mail from an ASP.NET web site was already quite easy, but by adding some Helper methods things are now easier than ever:

var customerName = Request["customerName"];     
var customerRequest = Request["customerRequest"]; 

// Initialize Mail helper
Mail.SmtpServer = "your SMTP host";
Mail.SmtpPort = 587;
Mail.EnableSsl = true;
Mail.UserName = "your user name here";
Mail.From = "your email address here";
Mail.Password = "your accound password";

// Send email
Mail.Send(to: "target email address here", subject: "Help request from - " + 
       customerName, body: customerRequest
);  

Being Social

It's also pretty easy to integrate social features in your web site. Sharing links with sites such as delicous is a one-line operation:

@LinkShare.GetHtml("LinkShare Example")

and integrating Twitter content in your site isn't too hard either. With this single line of code:

@Twitter.Profile("ImarSpaanjaars")

you get the following Twitter information embedded in your page:


Figure 8

It does this by emitting code also found in the Twitter Widget.

Is this Cool or What?

WebMatrix is currently in beta, so a lot will have changed by the time the product ships. However, this beta clearly shows the direction Microsoft is heading with this "stack". While working with the beta, I discovered a lot of cool features that will indeed make it easier for web developers to get on board on the Microsoft platform.

However, because things are so simple, "bad practices" may be just around the corner. Before we know it, we're back to the classic ASP era again and create bloated web sites with lots of mixed code, content and functionality. Also, SQL Injection may be around the corner again, just when we thought we had that pretty much covered with parameterized queries and ORM systems. I think it's up to the development and documentation teams, and the community around WebMatrix at large to come up with samples, tutorials and books that show how to use WebMatrix in the best and most secure way, focusing on best practices in web development rather than taking short cuts. For now, the documentation that ships with WebMatrix seems to be off to a good start.

Where to Learn More?

Microsoft just announced the beta of WebMatrix, so I am expecting many sites will start writing about it in the near future. The best place to get started with WebMatrix is by downloading the beta bits from the WebMatrix web site and start playing around with it. The documentation that you can also download is a great place to start your learning tour as it comes with many, easy to follow and copy-and-paste examples.

Welcome to the WebMatrix.... Have fun!


Where to Next?

Wonder where to go next? You can post a comment on this article.

Doc ID 547
Full URL https://imar.spaanjaars.com/547/welcome-to-the-webmatrix-introducing-microsofts-new-web-stack
Short cut https://imar.spaanjaars.com/547/
Written by Imar Spaanjaars
Date Posted 06/29/2010 12:55

Comments

Talk Back! Comment on Imar.Spaanjaars.Com

I am interested in what you have to say about this article. Feel free to post any comments, remarks or questions you may have about this article. The Talk Back feature is not meant for technical questions that are not directly related to this article. So, a post like "Hey, can you tell me how I can upload files to a MySQL database in PHP?" is likely to be removed. Also spam and unrealistic job offers will be deleted immediately.

When you post a comment, you have to provide your name and the comment. Your e-mail address is optional and you only need to provide it if you want me to contact you. It will not be displayed along with your comment. I got sick and tired of the comment spam I was receiving, so I have protected this page with a simple calculation exercise. This means that if you want to leave a comment, you'll need to complete the calculation before you hit the Post Comment button.

If you want to object to a comment made by another visitor, be sure to contact me and I'll look into it ASAP. Don't forget to mention the page link, or the Doc ID of the document.

(Plain text only; no HTML or code that looks like HTML or XML. In other words, don't use < and >. Also no links allowed.