Using WebMatrix's OData Helper

OData, or Open Data Protocol, and a way to query data from a variety of sources including databases, file systems, CMS, and websites. With the OData protocol, a user can query data over HTTP and receive a response in several formats including XML and JSON. It also has the ability to order and filter the queried data.

In order to make querying data easier, there is a OData helper for WebMatrix. This helper is easy to install and simple to use. But, before we can get started using OData, we must download and install WebMatrix. If you already have WebMatrix installed you can skip the next section.

Creating your WebMatrix website

If you need help downloading and installing WebMatrix, it may be a good idea to read Getting Started with WebMatrix. The article provides step by step instructions on installing WebMatrix

Once you launch WebMatrix, you'll see the Welcome Screen. Here you have many options on creating your website.

For this tutorial, we will be using an Empty Site template. Click the "Site from Template" option. Here you will see all of the template options WebMatrix gives you. Click the "Empty Site" template and give your site a name.

Clicking "OK" will cause WebMatrix to create you new website. You will be taken to your Workspace. This contains information about your local host as well a provides resources on developing your site.

You’ll notice that WebMatrix allows you to move between different workspaces by selecting the buttons on the left hand side. At present the Site button is selected which gives you details on your web site, such as the URL of the site, and other tools that you can use such as monitoring your site requests. You can look into this workspaces as you work but for this article, we will be working with our Files workspace. To get to your Files workspace, click the “Files” tab on the lower left hand of WebMatrix.

Once in your Files workspace you can see all your files. Since we chose the Empty Site template, we do not have any files. Let’s create a new file for our website. The "new" button on the menu ribbon allows us to create new folders and files for our website.

You will see all the different file types that we could create. Choose the .cshtml file.

We now have an empty, HTML5 valid page waiting for us to add code. You may be wondering why we created a .cshtml file instead of a traditional .html file. A .cshtml file is a new, special file type for WebMatrix. This type of file can contain the usual contents of a webpage including HTML and JavaScript code but, what sets it apart from a regular .html file is that it can also contain code for programming webpages. .cshtml files let you embed ASP.NET code into your HTML page using the new Razor syntax (which is most commonly denoted using @ - similar to PHP's $).

Razor code can go anywhere on your webpage. Blocks of code (written between @{ }), single line statements, and even single variables can be put anywhere, just make sure you have the correct syntax! If you want a more in-depth introduction to WebMatrix, you can find numerous resources on the subject including the asp.net website.

Now that we have created a website with WebMatrix, we can download the OData helper and get starting consuming an OData feed on our website.

Download the WebMatrix OData Helper

The OData helper can be found at odatahelper.codeplex.com. It can be used in either WebMatrix or ASP.NET webpages to access and expose data from OData feeds. The OData Helper Codeplex page has some useful resource links and documentation.

Click the download button on the top right to download the OData helper.

Once you click the link, you will be asked to agree to the license terms.

A pop up will appear at the bottom of your screen asking to open or save the file. For this, we can choose the open file.

A windows explorer window will open up with all the OData Helper files. Including in these files are an OData Helper example. This example is the one shown in James Senior's OData Helper video. This may be a good video to check out before working with the OData helper yourself.

You can browse through and see all of the files included in the download. The only files required to use the helpers can be found in the "bin" folder.

If you open the bin folder you will see two different .dll files. The .dll file we need is Microsoft.Web.Helpers.OData.dll

Now we need to add this .dll helper file to our website. Note that our .dll file was found in the bin folder when we downloaded it. When you add the helper to your website it always needs to be located in the bin folder of your website. Since we don't have a bin folder (since we choose the empty site template), we need to create one. You can do this by clicking on the "new" icon on the menu ribbon and choosing "new folder."

You will need to give your new folder the name of bin. You will now have a bin folder for your website.

Adding the helper to your bin folder is quite simple. All you need to do is right click on the bin folder and choose "Add existing file."

This will open a pop up. Navigate to where your OData helper is located. I saved mine to my desktop in order to make it easier to find. Make sure that you choose the Microsoft.Web.Helpers.OData.dll file.

Now your OData helper has been added to your bin folder and we can get started using it on our website.

Using the OData Helper

Before we can use the OData Helper we must declare that we are using it. All you must do is add a @using reference to your file. At the top of your .cshtml file, add:

@using Microsoft.Web.Helpers

This let's our webpage know that we are going to use our OData Helper class. Now we can use our OData helper. Making an OData request is similar to making making any web request using a request url. For this example we will be using the eBay OData feed. eBay has a great resource on all the different OData feeds and filtering options. This is helpful if you have little experience using Linq syntax. It can be found at ebayodata.cloudapp.net/docs.

First, let's look at the most basic OData feed that we can consume: searching for eBay items. We could also search by Categories or Deals but for this example we will be searching by Items.

Our OData helper code can be placed directly after our @using namespace code, in the <head> of our page or in the <body>. That's the beauty of Razor code, it can be placed anywhere in your webpage! Add to your .cshtml file:

@{
     var result = OData.Get("/ebayodata.cloudapp.net/Items?search=Sennheiser");
     var grid = new WebGrid(result);
}

In addition to putting our OData feed into a variable, we create a WebGrid with our OData results. The WebGrid is another WebMatrix helper. The WebGrid helper generates an HTML table that displays your data. In this case, we will be putting our OData into a table. A nice thing about the WebGrid helper is that it allows for formatting so we can add some CSS style to our table (but we'll get to that later).

Despite making a new WebGrid with our OData results, we need to render our WebGrid on our page. This requires another line of code. Add between <body> tags,

@grid.GetHtml()

Now that we have our OData feed and our WebGrid code, we can run our page to see what our results would be. You can run your page by clicking the "run" icon on the menu ribbon. You can choose what browser to run your page in or have it run in your default browser.

Right now our page is a little overwhelming. There are so many different table columns that we have to scroll to the right to see it all. There are also some columns present with information that we don't necessarily want or need. You also may notice that we retrieved so many items that it goes on for pages and pages. We can solve this problem first by filtering out results.

Let's filter our results by only retrieving items that are posted under $100. This would still yield a great deal of responses so let's only retrieve the top 5 matches. Our OData request would look like this:

var result = OData.Get("http://ebayodata.cloudapp.net/Items?search=Sennheiser&$filter=CurrentPrice%20lt%20100&$top=5");

You can choose different filtering choices. Great examples of the different options can be found on the eBay OData page.

Let's run our page with our new request and see our new results.

Now we have the top 5 items. We still have all the data visible on our page which we may not want to be visible. With the WebGrid helper we can specify what columns to build in the table and what data to fill the columns with. Let's add that code now.

columns: grid.Columns(
     grid.Column("Title", "Product Name"),
     grid.Column("GalleryUrl", "Product Image"),
     grid.Column("CurrentPrice")
)

Now we will have a table with three columns - title, gallery url and current price. The first string is the OData element name and the second string is the header name of the column. It is not required to have make your own column header but some element names may not make the best header names. Let's run our page again to see our new table.

Now our table only has three columns but it still isn't much to look at. You also make notice that instead of an image of the product we simply have a image url. Wouldn't it be nice if we could display the product image as well as a link to the item's page on the eBay website? Well we can in a little bit more of code. Let's add the code now. Update your WebGrid code:

@grid.GetHtml(
   columns: grid.Columns(
      grid.Column("Title", "Product Name", format: @<a href="@item.ViewItemUrl">@item.Title</a>),
      grid.Column("GalleryUrl", "Product Image", format:@<img src="@item.GalleryUrl" />),
      grid.Column("CurrentPrice", "Price")
   )
)

To make the title element column a link we change the column format by specifying it as a <a> with the value as the ViewItemUrl element as the reference. With the item image we use the same idea but instead of specifying it as a <a>, we specify it as a <img> with the GalleryUrl value as the reference. These two simple additions to our WebGrid adds more functionality to our page.

Now the last thing we can do is add some CSS to style our table. We can add some attributes to our web grid in order to specify the style our table: tablestyle and headerstyle. We could add our CSS as an external file or directly to our file. For this example, we'll add a <style> tag to the <head> of our page. Add to the <head> of your page:

        <style>
            .table {margin: 5px; }
            .header a { text-decoration: none; color: White;}
            .header { background-color: #D0D0D0;  }
            .table th { border: 1px solid black; }
            .table td { padding-left: 5px; padding:right: 5px; border: 1px solid black;}
            .table td a { text-decoration: none; color: Black;}
        </style>

You can change the CSS to however you want to style your table. Now all we need to do is apply the table style to our Web Grid. Change your grid so it has the style attributes:

@grid.GetHtml(tableStyle: "table", headerStyle: "header",
            columns: grid.Columns(
                grid.Column("Title", "Product Name", format: @<a href="@item.ViewItemUrl">@item.Title</a>),
               grid.Column("GalleryUrl", "Product Image", format:@<img src="@item.GalleryUrl" />),
               grid.Column("CurrentPrice", "Price")
            )
)

Now if we run our page our table will have the CSS style applied to it.

Our entire code now looks like this:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Using Ebay's OData and WebMatrix's OData Helper</title>
        <style>
            .table {margin: 5px; }
            .header a { text-decoration: none; color: White;}
            .header { background-color: #D0D0D0;  }
            .table th { border: 1px solid black; }
            .table td { padding-left: 5px; padding:right: 5px; border: 1px solid black;}
            .table td a { text-decoration: none; color: Black;}
        </style>
    </head>
    <body>
        @using Microsoft.Web.Helpers
        @{
           var result = OData.Get("http://ebayodata.cloudapp.net/Items?search=Sennheiser&$filter=CurrentPrice%20lt%20100&$top=5");

            var grid = new WebGrid(result);
        }        
        
        @grid.GetHtml(tableStyle: "table", headerStyle: "header",
            columns: grid.Columns(
                grid.Column("Title", "Product Name", format: @<a href="@item.ViewItemUrl">@item.Title</a>),
               grid.Column("GalleryUrl", "Product Image", format:@<img src="@item.GalleryUrl" />),
               grid.Column("CurrentPrice", "Price")
            )
        )
    </body>
</html>

Using the OData Helper was that simple. We only needed one 1 line of code to get our OData feed. For this tutorial we choose to use the WebGrid helper to put our results in a table. This is not the only way your can deal with your OData feed but is merely one of the more simple ways.

Additional Resources

Download WebMatrix http://www.microsoft.com/web/webmatrix/

Learn how to Download and Install WebMatrix http://www.microsoft.com/web/post/web-development-101-part-1-getting-started-with-webmatrix

Learn more http://www.microsoft.com/web/post/Web-Development-101-using-WebMatrix

Create a website with a WebMatrix site template http://www.microsoft.com/web/post/create-a-website-from-a-webmatrix-site-template

Publish your website http://www.microsoft.com/web/post/how-to-publish-a-web-application-using-webmatrix

Learn to download, edit and republish your website http://www.microsoft.com/web/post/download-edit-and-republish-your-website-with-webmatrix

You can discuss this article using the adjacent Facebook talkback.

For technical questions please visit our discussion forums, where we have a vibrant community of developers like you, as well as Microsoft engineers who are ready to answer your questions!