New PayPal Helper for WebMatrix

This week I’ve been at the PayPal Innovate Conference in San Francisco where Microsoft and PayPal have been talking to thousands of developers about the work we have been doing to create the easiest way to build apps that use PayPal for payments.  Today we are releasing the PayPal Helper for WebMatrix (in beta) which provides a simple way to do PayPal payments from the websites you build in WebMatrix.

What’s included in the PayPal Helper?

The helper we are shipping today, provides methods for the Button Manager API and Adaptive Payments API which are two of PayPal’s most popular APIs.  Here’s what PayPal says about both:

  • Button Manager APIs let you create, manage, edit, and delete Website Payments Standard buttons. Create payment buttons that let customers purchase single or multiple items, make donations, set up recurring payments, or buy gift certificates.
  • Adaptive Payments enable developers to build apps that process transactions. App builders can control the entire transaction within a single interface.
Downloading and installing the PayPal Helper
  1. Download and install WebMatrix
  2. Download the assemblies for the Helper (PayPal.dll, paypal_base.dll, log4net.dll)
  3. Create a new website or template in WebMatrix
  4. Create a bin folder off the root
  5. Copy and paste the assemblies into the bin
  6. You’re done!
PayPal Helper: Using Button Manager

Note – If you’re not familiar with the Button Manager API from PayPal, check out PayPal’s developer portal to find out more

The first thing you need to do is initialize the helper with your PayPal account credentials.  You can of course do this inline in the page, but the recommended option is to place the init call in your _AppStart.cshtml page so that it is called once when the app runs.  Here’s the init call code:

           “[API Username]“,
           “[API Password]“,
           “[API Secret]“,


Next, to create a button on the PayPal side, call the method below.  When the Create AddToCart Button is fired, it returns the HTML code needed to display the button which we can then save to the database. We’ll typically use this HTML when we display the product detail page.

var payPalButton = PayPal.AddToCartButton.Create(
                                           Business : “[insert your sandbox account]“,
                                           ItemName : name,
                                           Amount : price.ToString(“N2″));


Now, if you login to PayPal (remember to use your Sandbox account if you have been using that) and click the “Profile” link and then “My Saved Buttons” under Selling Preferences, you will be able to see the button you have just created:


PayPal Helper: Using Adaptive Payments

Note – if you are not familiar with the Adaptive Payments service from PayPal, check out their developer portal for more information

I’m a big fan of the Adaptive Payment API because it has some cool features like Split Payments which allow you to pay other people “behind the scenes” without the customer knowing.  This is great if you have suppliers that you want to pay whenever an item gets sold through your online application but you don’t want to bother the customer with the details or let them know what you are paying your suppliers Smile

First up you’ll need to Initialize the profile, just like we did for Button Manager.  Here’s the code for that:

       “[API Username]“,
       “[API Password]“,
       “[API Key]“,
       “[App ID]“,
       “[PayPal User Email Address]“


Next, we prepare the payment by setting up a single instance of a “receiver” which will the store that is receiving the payment.  After that we setup a list of receivers, which represents our suppliers (or other people that we need to pay after the transaction).  Up top I’ve done a quick calculation to give the supplier 10% of the product price, of course you would typically pull this information from a database where you stored the amount you want to pay them.

Once all that is setup we then call the PayPal.ChainedPay.Execute method passing in the receivers, an empty string (this is the sender of the payment – to be specified on PayPal’s side) as well as some information on the transaction. 

PayPal returns a response from which we can get a PayKey which represents the transaction on the PayPal side.  We then redirect the user to PayPal’s site, passing in the PayKey in the querystring so that PayPal knows how the transaction has been setup.

var supplierAmount = decimal.Round(product.Price * .10m, 2);
        var MyStore = new Receiver();
       MyStore.amount = product.Price; = “[Store Email]“;
        var Suppliers = new List<Receiver>();
       var Supplier = new Receiver(); = “[Supplier Email]“;
       Supplier.amount = supplierAmount;

       PayPal.ChainedPay.Language = “en_US”;
       PayPal.ChainedPay.CancelUrl = “”;
       PayPal.ChainedPay.ReturnUrl = “”;
       PayPal.ChainedPay.CurrencyCode = “USD”;
       var response = PayPal.ChainedPay.Execute
           (MyStore, Suppliers, “”, “Test Payment”, “″, “MyDevice”);
       if (response == null) {
       var payKey = response.payKey;
       var redirectUrl = “” + payKey;           


This is what the consumer sees – note it’s just one line item to James’ test store.


Thanks to Chained Pay, the store sees this in it’s transaction log.  Note that our supplier has been paid automatically.


Open source

The code for the helper is based on the existing PayPal Base library for .NET that PayPal ship as part of the developer SDK.  This is already under the Apache license so it seemed natural to continue the tradition and release the helper in CodePlex under the Apache license.  You can download it here.

Future work

As this is a beta there’s a few items that we wanted to polish up for the final version.  

  • Remove dependency on Log4Net
  • Merge PayPal base assembly code with the new Helper assembly
  • Consolidate initialization methods for Button Manager and Adaptive Payments

As always please contact me if you have other suggestions, or leave feedback on the Codeplex project site.

New Facebook Helpers in WebMatrix Beta 2

Today we launched WebMatrix Beta 2 with a bunch of new features.  Here are my favorites:

  • Themes – quickly switch between different themes on your website
  • New HTML5 Templates in the box – rounded corners, transitions, sexy HTML5 templates. yum.
  • NuPack Package Management – get the bits you need, when you need em
  • New @Helper Syntax – adding helpers is now even easier

The new @Helper syntax makes it super easy to create your own helpers for WebMatrix.  Why would you want to do that? Well, there’s a couple of reasons.  Firstly, as a timesaver.  If you find yourself writing the same code or HTML time after time in your websites, it might be time to package up your code in a reusable Helper that you can utilize throughout your websites instead of writing the same thing over and over again and wasting time.  Secondly, if you are trying to foster a developer community that can use your service or website, then creating WebMatrix Helpers to make their life easier is a smart thing to do – because it removes friction for people to use your service.

Take the new Facebook Social Plugin Helpers in WebMatrix Beta 2 as an example.  They make use of the new @helper syntax to make it easier for developers to add social widgets to web pages.  The way you get these helpers is also worth mentioning, because it highlights a use of the NuPack technology that we announced today also.  Facebook’s Social Plugins Helper includes shortcuts to the following social widgets:

  • Login Button
  • Like Button
  • Comments
  • Recommendations
  • LikeBox
  • Facepile
  • LiveStream
  • ActivityFeed

As well as the ability to easily add metadata which shows up in rich ways across Facebook.

Getting your Helpers using NuPack

NuPack is an open source project driven by Microsoft that provides package management for developers in WebMatrix or Visual Studio 2010.  Within WebMatrix there is a package management page that you can visit where you can manage which packages are installed in your website projects.  With NuPack, it’s super easy to get Helpers and other things you’ll need to develop your website.

Note -  the current structure of our website if we create a new website from template.  Inside our app_data folder we have a bunch of folders including packages.  This is where the assets for our packages live.  We can see that we already have microsoft-web-helpers.1.0 installed by default and this package provides Helpers like Twitter, ReCapture and more.  There is also a packages.config file which contains information which points WebMatrix to the packages installed in App_Data.


To manage the packages installed in our website, we need to get to the admin page by simply navigating to http://localhost:xxx/_admin where xxx is your port number.  (Note – by default this is only enabled when running websites locally, as a security precaution).  If it’s the first time you’ve visited the page, you’ll be asked to create a password, remember this for future visits to the package manager page.


Next, you’ll be presented with a list of packages that you can install to use within your website.  Clicking on the Install button next to the Facebook.Helper 1.0 will install the files and pre-requisites for the helper to work correctly.  In the case of the Facebook Helper there are no dependencies however.



Once installed, the package “explodes” (in a useful, not violent way) in your website, installing various assets.  If we now look at the structure of the website in WebMatrix we see the Facebook Helper package has been installed successfully:


The most important asset is the Helper itself – FacebookSocialPlugin.cshtml and you can see that it was installed under the App_code folder in the root of website.  In this particular helper, we’ve also included some docs which explain how to get started as well as a full reference for all the methods in the helper.

To get to the docs just navigate to http://localhost:xxx/facebook/docs/starthere.htm

Note – There is already a Facebook Helper included in the Microsoft-web-helpers library which provides a shortcut to adding the Like Button to your website.  The FacebookSocialPlugin helpers has the like button as well as all the other Facebook Social Plugins and other good stuff like Open Graph etc.  In the next release we’ll merge the two Helper libraries so they are consolidated.

@helper syntax

Let’s explore the Facebook Social Plugin Helper a little more to understand how to use the @helper syntax.  The naming of the FacebookSocialPlugins.cshtml file is a good place to start.  This name will be taken as the class name at runtime, so the developer will use FacebookSocialPlugins.Foo() when using the helpers within the file.  Exploring the file, we see that all the methods use the @helper syntax, which mixes markup and code so that it’s possible to build up quite complex HTML and then inject parameters from the method or from calculated values in the helper code itself. 

Let’s take the helper method “GetInitializationScripts” as an example.  This method emits the JavaScript required by Facebook to allow their Social Plugins to work and must be added to every page that wants to use the plugins.  It’s not a trivial amount of script and before the Helper I would have to goto Facebook’s developer portal, hunt it down and copy and paste into every page.  Now with the Facebook Social Plugins Helper I can simply add the method to my _Layout.cshtml page, and by default it’s included on every page.  That’s a nice timesaver.

@helper GetInitializationScripts() {
   <div id="fb-root"></div>
   <script type="text/javascript">
       window.fbAsyncInit = function() {
           FB.init({appId: '@FacebookSocialPlugins.AppId', status: true, cookie: true, xfbml: true});
       (function() {
           var e = document.createElement('script'); e.async = true;
           e.src = document.location.protocol +
       function loginRedirect(url) { window.location = url; }

Notice how we inject he AppId from the FacebookSocialPlugins class?  This notion of mixing code and markup within a class method is very powerful and useful in lots of ways.  There’s a couple additional steps that you must do in order to have the Social Plugins working including calling the following method in _AppStart.cshtml.

   FacebookSocialPlugins.Initialize("[Your App Id]", "[Your App Secret]", "bakery");

Secondly you must register the Facebook namespace in _Layout.cshtml which tells the page about the Facebook markup:

<html xmlns="" @FacebookSocialPlugins.FbmlNamespaces() >


Normally this would be a copy and paste from the depths of the Facebook developer portal, now it’s simply a case of using the Helper and you’re done.

This then clears the path for us to easily add Facebook’s Social Plugins to a WebMatrix website:



Results in:


It’s important to note that some Social Plugins require your site to be published to an external host that Facebook can communicate back and forth to.

I recommend checking out the documentation which comes as part of the Helper NuPack for more information on getting started, simply press the “run” button in WebMatrix  with startHere.html opened to browse the docs.


Other good reading on WebMatrix Beta 2

Top Links to get started with WebMatrix

WebMatrix is everything you need to build Web sites using Windows. It streamlines Web site development and makes it easy to start Web sites from popular open-source apps.

Getting Started
  1. Download WebMatrix
  2. Top 10 features for Web Matrix
  3. Twitter Archive of everything WebMatrix
  4. Scott Gu’s Blog Post on WebMatrix
  5. API Reference Guide
  6. ASP.NET Web Pages Forum
  7. How to Create an ASP.NET Application from Scratch Using WebMatrix Beta
  8. Web Matrix eBook
  9. FAQs for Open Source and Free web applications
  10. Get help in the forums
Find Web Hosting for your projects

Microsoft’s Web Hosting Gallery

Make Suggestions and Submit Bugs

Help us make WebMatrix better! Make a suggestion or submit bugs to the team.

Pragmatic Press and Blog Coverage of Web Matrix

Microsoft Web Matrix: What’s In It for Dev Professionals? (Michael K Campbell)
WebMatrix – A Path To Enterprise Web Development? (David Hayden)

jQuery Templating in the wild

It seems like longer, but it’s only been 6 months since we announced that Microsoft was going to start contributing to jQuery instead of developing our own JavaScript library.  Today, Scott Guthrie announced that we’ve had our code checked in to the main branch of the jQuery project – you can read more about that on his blog and also check out the Web Camps TV interview I recorded with Stephen Walther on the subject.  John Resig has also confirmed that jQuery Templates will ship as an official plugin in v1.4.3 and then in the core library in v1.5.  (Data-linking will also be shipped the same way).

Check out the Web Camps TV interview with myself and Stephen Walther where we demo some of the new features:

Get Microsoft Silverlight

Holy miracle, Batman!? Microsoft are contributing to open source!


Yes that’s right, Microsoft are contributing to jQuery, which is an open source project.  That means we have real life developers working on shipping code – you can see what they’ve been up to on github.  Boris Moore the lead dev on our contributions has been writing up his thoughts on working at Microsoft on an open source project which make for some interesting reading. He also provides some details on using the templating engine and some of the advanced features that all templating ninjas should know.

Why use jQuery Templates?

There are basically two reasons to use jQuery Templates:

  1. Performance
  2. Maintainability of your code

On Performance. This benefit comes in two flavors, user experience and bandwidth.

First, let’s discuss user experience.  Modern websites are behaving more and more like desktop applications, with data that is constantly being refreshed with no user interaction.  Think about Twitter or Facebook and how they are regularly pulling data from the server to provide a refreshed look automatically.  jQuery Templates make it simple to declare the shape of your HTML and then insert fresh data to them, appending the resultant HTML to the DOM where appropriate.

Secondly, there’s bandwidth to think about.  Chatty applications that send/receive excessive amounts of data are bad for your bandwidth bills and bad for latency.  Instead of refreshing the entire page when just one portion needs updating, we can keep the noise down to a minimum with HTTP calls between JavaScript/jQuery and the server.    jQuery Templating allows you to take that data and then do something useful with it in an easy way. With this approach you are going to be making fewer calls and moving less data to the client.  There’s also the caching to think about as well – templates are cached on the client which will further reduce the data you are moving about.

On Maintainability of your code

Given that you’ve bought into rendering your data on the client-side because of the perf benefits, let’s also assume that your sanity is important too – this is another reason to use jQuery Templates.  It is of course possible do the job of jQuery Templates manually, using string concatenation to build up complex strings of HTML and injecting your data items as you go.  Rinse and repeat for each row of data you have and then have jQuery append it to your DOM.  However, there are more rewarding things in life than doing this, and if you’ve ever tried to match up HTML elements and tried to troubleshoot a complicated nugget of HTML you’ll know it’s pretty painful.  This is where templating helps by allowing you to declare a template inline in a code block so you can see the structure of the template at first glance (see examples below).  It’s also worth calling out that templates make it easy to separate the logic on the client into app, structure and style, i.e. JavaScript, HTML and CSS.  For example, in my applications I like to have all my templates in a JS file called templates which I reference in my app when needed.

Pop quiz: which is easier to understand? This template?

<script id="movieTmpl" type="text/x-jquery-tmpl">    
            <img src="${BoxArt.LargeUrl}" />
        <p>{{html Synopsis}}</p>        
        <input type="button" title="Buy tickets for '${Name}'" value="Add to cart…" class="buyButton"/>        

or this concatenated string?

<script id="movieTmpl" type="text/javascript">    
    var myString = "<div><div><img src=";
    myString += BoxArt.LargeUrl;
    myString += "/></div><strong>";
    myString += Name;
    myString += "</strong><p>";
    myString += Synopsis;
    myString += "</p><input type=\"button\" title=\"Buy tickets for\"";
    myString += Name;
    myString += " value=\"Add to cart…\" class=\"buyButton\"/>;
    myString += "<br/></div>";

Hopefully the difference is clear Winking smile

Who’s using jQuery Templates?

imageThese bits are pretty fresh so there are only a few examples of websites using them.  One early adopter is hiFi, a website publishing engine.  They take performance seriously which is why they chose to use jQuery Templating engine to render their comments to the client.  The team at hiFi have also written up a really nice post on the subject of jQuery Templates.

To get started with templates I recommend checking out the jQuery API documentation and also the samples that Boris has created on  Rey Bango also has some great tutorials on the different ways you can declare templates too.

Web Camp LA–Trip Report

“This was the best training I’ve ever had, this was even more useful than TechEd” – Gabriel Cruz

Last Friday, Phil Haack, Jon Galloway and I ventured to Los Angeles to deliver a Web Camp at the downtown Microsoft office. 

What do you mean you drive on the other side of the road in the USA?

Photo – “What do you mean you drive on the other side of the road in the USA?”

Agenda and Content

After we got to the venue safely, we delivered an agenda on the following topics:


  • ASP.NET MVC 2 Fundamentals
  • Entity Framework (including a sneak peak of code-first)
  • Validation, Localization
  • ASP.NET MVC + jQuery, jQuery Templating, jQuery Globalization
  • ASP.NET MVC 3 and Razor

NEWS – You can now get the Web Camps Training Kit – September Edition!  This includes much of the content we covered at the event.  (note – we don’t have jQuery Glob or MVC 3 content, yet – that’s coming in November).

Feedback and areas for Improvement

Feedback from the event was great with average scores really high:

  • Overall Eval Score: 8 out of 9
  • Overall Instructor Score: 8.8 out of 9

This is what people told us about the event:

  • “Love the flexible agenda”
  • “One big advantage of the training is to learn first hand the trends in the industry and be able to direct appropriate amount of resources toward training and tools.”
  • “The course was great. As a web forms developer, I was particularly interested in learning more about MVC 2 and 3 and this course provided a huge amount of information. Not only was I able to see how sites can be created using MVC, but just by watching the instructors write code in Visual Studio I was able to learn tips and coding shortcuts that I didn’t know about before, and that will help me work more efficiently in the future.”
  • Great course. Even better that the price was free.
  • “Were the presenters good? It was friggen Phil Haack, Jon Galloway, and James Senior. They were great.”

There’s always areas for improvement, from what you said we need to work on some things for next time:

  • Make sure we have time for labs
    • Yes – we overran slightly due to questions but next time we’ll try and leave more time for hands-on building instead of doing the extra ASP.NET MVC 3 session
  • Get the wifi working
    • We hear you.  It’s always hard because we can’t control the venue and piping in dedicated broadband is super expensive.
  • Make sure the content is available at the event or on the website
    • Yes – due to timing the Web Camps Training Kit September Edition wasn’t available, that shouldn’t be an issue moving forward

We are on the cusp of releasing more dates for even more Web Camps, around the world. I’m very excited about this and I’ll have more news on this very soon! For all the information make sure you follow @jsenior or @webcamps on Twitter and check the website.

Web Camps Training Kit – September Edition

The Web Camp in Los Angeles was a great success last Friday with Phil Haack, Jon Galloway and myself imparting a raft of knowledge on ASP.NET MVC 2, jQuery, Entity Framework Code-first, ASP.NET MVC 3 and Razor.  However, there’s little time to pat ourselves on the back – because this week marks the launch of the September Edition of the Web Camps Training Kit!

Online and available as a download

The previous version of the Web Camps Training Kit was only available as a download, but we listened to your feedback and are now publishing it online too!  Choose your flavor below:

Browse the content online

Download it Now

What’s new in the Web Camps Training Kit – September edition?

The goal for Web Camps is to provide great training events and an accompanying Training Kit so that web developers have thing they can rely to build websites and apps on the Microsoft Web Platform.  To be a complete web developer, you have to understand many different types of technology, not just the server side.  You also need to know technologies like jQuery, OData and when/how to leverage Web Apps like Umbraco, Kentico, DotNetNuke and more.  As things move so fast, you’ll also need to keep in touch with the latest developments in HTML 5 and how to take advantage of them in the websites you build.

So, in the September edition we are starting to introduce some new technologies areas that help you to keep on the cutting edge.  This is only the beginning and in future editions we will be constantly adding to future versions of the Training Kit.  Here are some new things I would like to highlight:

  1. jQuery

    Working with the .appendTo() team we’ve put together 3 jQuery sessions with presentations, demo scripts and source code.  This content covers some of the fundamentals of jQuery and then extends using Ajax as well as jQuery Templates and jQuery UI.
  2. IE 9 & HTML 5

    With the IE9 Beta just out the door, we’ve provided you some presentations on how to develop on IE9 as well as some of the enhancements the team have made on performance.  This is useful background material and we’ll be following this up with more content in the next release.
  3. ASP.NET MVC 2

    The ASP.NET MVC 2 content has been refreshed and we’re now basing all the content off the MVC Music Store.  There are presentations, labs and demo scripts that walk you through build the site and we’ve also provided a bonus lab on how to start adding Tests to the project.
  4. Web Apps

    The beauty of Web Apps are that they install really easily and they get you to 80% of a completed solution with little effort.  You can customize and tweak them the rest of the way for your own requirements to build complete solutions for customers is no time at all.  In this release we’ve teamed up with Umbraco, Kentico and DotNetNuke to provide presentations, videos and labs for you to get started building solutions.

  5. OData

    OData is the new standards-based web protocol for querying and updating data.  If you are writing an API for your website, it’s worth seeing how you can leverage OData to give developers a clean and familiar way to access your data.  Or, if you are interested in consuming one of the many OData services out there then there are a bunch of SDKs out there to get started in your language.  We provide an intro presentation into OData with more content coming soon to help you learn the programming syntax.

Phew – there’s lots of new content in this release and it’s been fun pulling it all together.  We’ll continue to add more as well as update existing pieces as they become out of date.  Of course, if you have feedback we’d love to here it – please get in contact here.

Don’t forget about the events – you can get expert training by registering for a Web Camp here.  We will be releasing a raft of new event dates very soon.  We are going large – stay tuned!

Web Camp LA–Results of the agenda poll

For the Web Camp in LA we asked you what you wanted to hear about at the event.  This is always a bit risky because you end up not being able to please everyone but it was clear that there were some popular topics out there.  Here are the results:


Phil, Jon and I spend time last week to come up with an agenda that attempts to combine some of the most popular topics, like jQuery, MVC 101, Data Access and Modelling as well as Ajax, and Client-side Validation.  We think we’ve done that pretty well and I’m please to present the agenda for Web Camps LA:



08:30-09:00 Arrival & Registration


ASP.NET MVC Fundamentals: MVC 101


ASP.NET MVC Fundamentals: Data Access and Modeling with Entity Framework


Break for 15 minutes


MetaData and Validation, Localization


Lunch for 45 minutes


MVC and Ajax, jQuery Templating, jQuery Globalization



17:00 Leave

Depending on how we are feeling and audience demand, we might also squeeze in an extra bonus session on ASP.NET MVC 3 and Razor – Phil’s been wanting to dazzle everyone with Razor syntax Smile

Here’s a sneak peak of me and Phil talking about Razor and MVC3 here.

Ask the expert on Web Camps TV: Rey Bango

Every week we give you the chance to ask the experts questions on Web Camps TV when we’re in the studio.  To ask a question – use the Facebook Live Stream below during the “on air time” and we’ll attempt to answer as many questions as possible.  The show will be aired at a later date.

Today, Friday 27th at 4pm PST we have Rey Bango in the Channel 9 studio.  Rey is a member of the jQuery Core Team and also works at Microsoft as a all around web ninja kinda guy.  Ask your questions below and we’ll get them answered!


Web Camps L.A.– Sold Out in 48 hours (UPDATED)

****UPDATED 8/27/2010 2:20pm****
We have upgraded to a bigger room and there are currently tickets available for the Web Camp in LA. If you were on the wait list you will be automatically assigned a ticket.  If you’ve not yet signed up – make sure you do quickly!

LAWe released the tickets just under 48 hours ago and Web Camp LA is sold out!  That’s good and bad news, right?! For those of you who haven’t yet signed up, don’t be too distressed.  We are currently looking for a bigger room so that we can release some more tickets.  I’ll post an update once we’ve secured the room – fingers crossed!

Remember we are crowdsourcing the agenda – here’s the poll results so far.  Looks like jQuery and ASP.NET MVC 101 is out in front.  Be sure to vote so you hear the right content!


Make your voice heard – take the poll and let us know what content you want!

New: Windows Azure Storage Helper for WebMatrix

Hot on the heels of the OData Helper for WebMatrix today we are pushing out a new helper into the community.  The Windows Azure Storage Helper makes it ridiculously easy to use Windows Azure Storage (both blob and table) when building your apps.  If you’re not familiar with “cloud storage” I would recommend you take a look at this video where my pal Ryan explains what it’s all about.  In a nutshell, it provides infinitely simple yet scalable storage which is great if you are a website with lots of user generated content and you need your storage to grow auto-magically with the success of your apps.  Tables aren’t your normal relational databases – but they are great for simple data structures and they are super fast.

You can download the helper from the Codeplex website.

Get started in 60 seconds
  1. If you haven’t already got one, sign up for a Windows Azure account
  2. In the _start.cshtml file setup the helper for use with your account by adding this code:
    1. @using Microsoft.Samples.WebPages.Helpers
    2. @{
    3.     WindowsAzureStorage.AccountName = "youraccountname";
    4.     WindowsAzureStorage.AccountKey = "youraccountkey";
    5. }

  3. Download the latest Windows Azure Storage Helper Binaries
  4. In your WebMatrix project, create a folder named "bin" off the root
  5. Copy the Windows Azure Storage Helper Binaries there
  6. Check out the documentation
  7. Start using Windows Azure Storage Tables and Blobs from WebMatrix with the Helper!

There are loads of use cases out there for blob and table storage.  You just need to look at of the popular startups like Facebook, Twitter, YFrog, Foursquare, Dropbox who all use this type of storage to gain great scale and performance.

How to use the helper

With the helper we’ve provided a bunch of methods that make common operations really easy so that you can that in your WebMatrix apps.  Here are some of my favorite examples:

1. Getting a row from a table – notice how we can just dump the result into a WebGrid and have it render our table for us.

  1. @using Microsoft.Samples.WebPages.Helpers
  2. @{
  3.     var rows = WindowsAzureStorage.GetRows("JamesTable");
  4.     var grid = new WebGrid(rows);
  5. }

2. Updating a row in a table – first we get the individual row, making sure to pass it the partition and table name.  Next we make a change to an item, then update the table.

  1. @using Microsoft.Samples.WebPages.Helpers
  2. @{
  3.     var row = WindowsAzureStorage.GetRow("JamesTable", "partition1", "row1");
  4.     row.Name = "James Senior";
  5.     WindowsAzureStorage.UpdateRow("JamesTable", row);
  6. }

3. Uploading a file into blob storage – I like to use this in combination with the FileUpload helper that we ship with WebMatrix.  You can pass a stream, binary file or text string into the helper method and it’ll be placed in the blob address you specify.

  1. @using Microsoft.Samples.WebPages.Helpers
  2. @{
  3.     var uploadedFile = Request.Files[0];
  4.     WindowsAzureStorage.UploadBinaryToBlob("MyContainer/" + uploadedFile.FileName, uploadedFile.InputStream);
  5. }

4. To grab the blob, use one of the download methods like DownloadBlobAsText or DownloadBlobAsText.

@using Microsoft.Samples.WebPages.Helpers
   // reference to my blob
   var blobRef = "MyContainer/foo.txt";

   // gets the blob as text
   var astring = WindowsAzureStorage.DownloadBlobAsText(blobRef);
   // gets the blob as a byte array and puts it in the
   var bytes = WindowsAzureStorage.DownloadBlobAsByteArray(blobRef);
   // Send the response so the user can download the file
   Response.AppendHeader("Content-Type", "application/octet-stream");
   Response.AppendHeader("Content-Disposition:", String.Format("attachment; filename={0}", HttpUtility.UrlPathEncode(blobRef)));

Here’s a video where I walk through how to do all this good stuff in detail:

Get Microsoft Silverlight


Future work

There’s some more features I’d like to add to the next version of this helper. I’ve started a discussion here about that – join the conversation if you have any ideas!  Here are the current ideas:

  • Error Handling (Windows Azure Tables)
  • Pagination and continuation tokens (Windows Azure Tables)
  • Lease/Snapshot/Copy Blob operations (Windows Azure Blobs)
  • Sharing Blobs (Windows Azure Blobs)
  • Delimiters (Windows Azure Blobs)
  • Client-side ordering (Windows Azure Tables)