Published on ONDotNet.com (http://www.ondotnet.com/)
 See this if you're having trouble printing code examples

Introducing ASP.NET Web Matrix

by Wei-Meng Lee & Brian Jepson

Back in the days of ASP 2.0 and 3.0, developers generally had two choices when it came to building Web applications. One was to use Visual InterDev, which came with Visual Studio 6.0. Another was to code everything by hand using a text editor. I didn't really have much experience using the former, as it didn't give me a good impression. Moreover, I had heard a lot of developers complain about its shortcomings. My choice then was to use a text editor (NotePad was a favorite, since it was free, but if I needed to edit big files, I would use an enhanced editor like UltraEdit or EditPad) to write ASP applications. Students who attended my Web development classes often asked the reason for not using a visual tool like Visual InterDev. My usual response was that coding everything by hand allows you to fine-tune the Web pages you are creating. Moreover, it really forces you to have a good understanding of HTML and the underlying ASP object models.

During the early days of the .NET Framework (during the beta 1 era), I still insisted on creating my Web applications using a text editor. If you were like me, you may remember that you needed to add the runat attribute to all of those <asp:> tags. The most popular example at that time was a demonstration of the ability of ASP.NET to automatically maintain the state of a Web application -- you chose something from a drop-down list box and click on a submit button, and voila! The selected item still remained selected! As you built more sophisticated applications, you realized that you could no longer code that quickly using just a text editor. How do you know whether a particular object has this property or method and whether is the method overloaded?

Visual Studio .NET Comes to the Rescue

Related Reading

ASP.NET in a Nutshell
By G. Andrew Duthie, Matthew MacDonald

Fortunately, Microsoft realized this problem and built a very useful tool known as Visual Studio .NET. In fact, building solid development tools has always been Microsoft's forte. Visual Studio .NET presents an integrated approach to developing .NET applications. Unlike its predecessor, Visual Studio .NET integrates the entire development environment into one. You can now build Windows applications, Web applications, Web services, Windows services, etc., using C#, VB.NET, and all supported languages, in one development environment.

The most significant innovation made by Microsoft, in my opinion, is Intellisense. It greatly simplifies the development process and significantly reduces the memory needed to work with the huge class library in .NET. Can't be sure if a property belongs to a particular object? What is the return type of a method? Intellisense will tell you straight away. For those hardcore programmers who eat the class library for breakfast, I know you can survive without Intellisense (see Brian Jepson's article "You Can Hack .NET Without Buying Visual Studio .NET"). But for the rest of us, Intellisense is a great help! (See Jose Mojica's Article "The Role of the IDE in Programming Languages.")

Though VS.NET speeds the development process, not everyone can afford it (though I think any .NET developer worth their salt should get a copy nevertheless). This issue has been slowing the adopting of .NET, to a certain extent, and Microsoft is well aware of this problem. Hence, Microsoft recently announced the launch of a new tool for building ASP.NET Web applications: the ASP.NET Web Matrix -- a community-supported, easy-to-use development tool for building Web applications. The ASP.NET Web Matrix is positioned somewhere between Visual Studio .NET and plain text editors. It is targeted at developers who are currently hand-coding their ASP.NET Web applications, by providing them with a useful tool to accelerate the development process. It is also used as bait to get new developers to try out ASP.NET. In this article, I will take a look at the capabilities of ASP.NET Web Matrix.

A Quick Tour of ASP.NET Web Matrix

You can download the ASP.NET Web Matrix from asp.net. This tool is very lightweight -- the download is a measly 1.1 MB, small enough to fit on a diskette and petite enough to run on your 128 MB (RAM) Pentium III. The package contains three main components:

Figure 1. The Class Browser

When you first launch ASP.NET Web Matrix, you will see the Add New File window (Figure 2):

Figure 2. Using ASP.NET Web Matrix

Under the Templates category, you have the following sections:

We will now run through some of the features of ASP.NET Web Matrix by building two sample Web applications.

Building a Web Application Using ASP.NET Web Matrix

Let's now build a Web application that consumes Amazon's Web service. For a more detailed discussion of Amazon's Web service, see Wei Meng Lee's "Using Amazon's New Web Services."

When the ASP.NET Web Matrix is launched, it will prompt you to add a new file. My intention is to use a DataGrid to bind the results returned from the Amazon's Web service. Hence I selected the Data Pages category and chose Data Report with Paging. Name the page Amazon.aspx (Figure 3).

Figure 3. Creating a new data page

By default, the page will contain the DataGrid control (and some HTML controls):

Figure 4. Default controls in Data Page

Like Visual Studio .NET, ASP.NET Web Matrix allows you to format the layout of the DataGrid control. To do so, simply click on the control and select AutoFormat in the Properties window:

Figure 5. Selecting the AutoFormat feature

Select a scheme that you like. After this, you are going to modify our DataGrid control by editing the HTML (select the DataGrid control and press Ctrl-T):

Figure 6. Modifying the DataGrid control

Insert the codes in bold:

<asp:datagrid id="DataGrid1" runat="server" 
  <FooterStyle forecolor="#8C4510" 
  <HeaderStyle font-bold="True" 
  <PagerStyle horizontalalign="Center" 
  <SelectedItemStyle font-bold="True" 
  <ItemStyle forecolor="#8C4510" 
    <asp:buttoncolumn text="Show Details" 

Our aim is to add an additional column to our DataGrid so that we can select a particular title and view its author and book cover image. Also, add in a Textbox and Button control so that users can search for titles. The familiar ToolBox (adding controls) is available in ASP.NET Web Matrix.

Our page now looks like Figure 7.

Figure 7. Our modified page

Once the design of the page is done, you can now proceed to coding the application logic. At the bottom of the ASP.NET Web Matrix, you will find four tabs:

Figure 8. Different views layout

Since ASP.NET Web Matrix does not support code-behind, the four tabs present a useful view to the different aspects of a Web page. You can either double-click on a page in design view or click on the Code tab to display the codes.

Coding the Application Logic

Since you are consuming Amazon's Web service, you need to build a proxy class to access it. The ASP.NET Web Matrix provides a Web service proxy class generator (Tools- >WebService Proxy Generator):

Figure 9. Generating the proxy class using the WebService Proxy Generator

What we have done is actually copy the WSDL document provided by Amazon and save it into the local drive (accessed using the file:// protocol).

You can also access the WSDL document at: http://soap.amazon.com/schemas/AmazonWebServices.wsdl. (If you are behind a proxy server, be sure to configure the proxy server in your IE settings; do not use automatic configuration settings.)

Also note that the proxy class must be generated and saved in the same directory as your ASP.NET page.

Let's now code the application logic for our application:

Step 1.

We first add two global variables:

Dim ds as dataset
Dim productsInfo as ProductInfo
Step 2.

We will define a subroutine named getTitles() to retrieve all of the titles from Amazon's Web service. First, access the Web service:

   Dim ws as new AmazonSearchService()

   Dim KeywordReq as New KeywordRequest()
   keywordReq.keyword = txtTitle.text
   keywordReq.page= 1

   productsInfo = ws.KeywordSearchRequest(keywordReq)

Step 3.

With the results stored in the productsInfo object, you will now convert the result into a Dataset object so that it can be bound to the DataGrid control:

ds = new dataset()

ds.Tables.Add(New DataTable("products"))
ds.Tables("products").Columns.Add("List Price")
ds.Tables("products").Columns.Add("Our Price")

Dim i as Integer
for i=0 to productsInfo.Details.Length - 1
    Dim row As DataRow = _
    row(0) = i + 1   ' to display #
    row(1) = productsInfo.Details(i).ProductName
    row(2) = productsInfo.Details(i).Manufacturer
    row(3) = productsInfo.Details(i).ASIN
    row(4) = productsInfo.Details(i).ListPrice
    row(5) = productsInfo.Details(i).OurPrice
Next i

Step 4.

Once the dataset is created, data bind it to the DataGrid control:

DataGrid1.DataSource = ds
Step 5.

We also need to define an event (SelectedIndexChanged) for the DataGrid control. This event is fired when the user clicks on the Show Details link.

Sub DataGrid1_SelectedIndexChanged(sender As Object, _
  e As EventArgs)

A call is first made to get the titles again:


The title is then displayed on the page:

   dim curr as Details
   curr = productsInfo.Details( _
   response.write ("<b>" & curr.ProductName & _
                   "</b><br>by: ")

Followed by the display of the authors:

   dim i as integer
   for i = 0 to curr.authors.length-1
      response.write (curr.authors(i).tostring)
      if i < curr.authors.length-1 then
         ' not the last author
         response.write (", ")
         response.write ("<hr>")
      end if
   next i

And then, finally, write an <img> element to display the book cover image:

   response.write ("<img src=" & curr.imageURLMedium & _
End Sub
Step 6.

There are three more subroutines you need to modify:

Sub Page_Load(Sender As Object, E As EventArgs)
    '----do nothing----
End Sub

Sub DataGrid_Page(Sender As Object, 
  e As DataGridPageChangedEventArgs)
    '----when the user clicks on the next page----
    DataGrid1.CurrentPageIndex = e.NewPageIndex
End Sub

Sub Button1_Click(sender As Object, e As EventArgs)
   '----when the user clicks on the Search button----
End Sub

That's it! When you press F5 to run your application for the first time, the accompanying Web server will prompt you:

Figure 10. Starting the Web server

You can now search for books from Amazon.com!

Figure 11. Testing the application

Customizing ASP.NET Web Matrix

One of the cool features of ASP.NET Web Matrix is its ability to add new components online. To add an online component, simply right-click on the toolbox and select Add Online Toolbox Components.... The Component Gallery lets you browse for components and controls online, and download them to your local machine.

Figure 12. Adding online toolbox components

Online components are grouped into categories. Select the catagory you want and see if there are any controls available. Installing a component to your ASP.NET Web Matrix is then a matter of clicking on the Install button.

Figure 13. Adding a new online component

Besides adding online components from the Web, ASP.NET Web Matrix also allows you to add commonly-used templates into the editor. You customize the templates using the WebMatrix.exe.config file. This file is found in the installation directory of ASP.NET Web Matrix, typically in c:\Program Files\Microsoft ASP.NET Web Matrix\v0.5.464\. (v0.5.464 is the build number of ASP.NET Web Matrix at the time of this writing, and it will change with subsequent releases.)

To add our Amazon Web application to the template, you need to add in the following elements (in bold) to the configuration file:

<templateDocumentType extension="asmx" 
    templateCategory="Web Services"
    name="Output Caching"
    createNewDescription="Output Cache Web Services."/>
<!-- ** End Web Service Templates ** -->

<!-- ** Start Consume Web Service Templates ** -->
<templateDocumentType extension="aspx" 
    templateCategory="Consume Web Services"
    name="Amazon Web service"
      "Web app to consume Amazon's Web service."/>
<!-- ** End Consume Web Service Templates ** -->

<!-- ** Start Security Templates ** -->
<templateDocumentType extension="aspx" 
    name="Login Page"
      "Login page for Forms Based Authentication."/>

You also need to create the following subdirectories within the Templates directory.

Figure 14. Creating the directory to store the template

As shown in Figure 14, you need to create the directory Consume Web Services/Amazon Web Service/Csharp (and VB). Copy the Amazon.aspx file that we created earlier, paste it into the VB directory, and rename it as NewFile.aspx.

Next, restart ASP.NET Web Matrix to cause it to reload the configuration file. You should now be able to see the updated template:

Figure 15. Updated template


I quite liked ASP.NET Web Matrix, but the lack of Intellisense is really a big limitation. One day, I hope, someone will write an add-in to it. Besides the features discussed in this article, ASP.NET Web Matrix also includes links to online discussion forums and newgroups. What's more, you can also link to your contacts using your Windows Messenger's contact list. Overall, the ASP.NET Web Matrix provides a viable development environment for developing ASP.NET applications. The tight integration with the online community makes seeking help relatively easy.

Wei-Meng Lee (Microsoft MVP) http://weimenglee.blogspot.com is a technologist and founder of Developer Learning Solutions http://www.developerlearningsolutions.com, a technology company specializing in hands-on training on the latest Microsoft technologies.

Brian Jepson is an O'Reilly editor, programmer, and co-author of Mac OS X Panther for Unix Geeks and Learning Unix for Mac OS X Panther. He's also a volunteer system administrator and all-around geek for AS220, a non-profit arts center in Providence, Rhode Island. AS220 gives Rhode Island artists uncensored and unjuried forums for their work. These forums include galleries, performance space, and publications. Brian sees to it that technology, especially free software, supports that mission. You can follow Brian's blog here.

ASP.NET in a Nutshell

Related Reading

ASP.NET in a Nutshell
By G. Andrew Duthie, Matthew MacDonald

Copyright © 2009 O'Reilly Media, Inc.