Sep 24

Adding the SimpleMembership provider to an ASP.NET Web Forms app

Posted in .NET, ASP.NET, C#       Comments Off on Adding the SimpleMembership provider to an ASP.NET Web Forms app

If you’re a long time user of ASP.NET, you’re probably aware that the out of the box providers have some limitations. For instance, you couldn’t really use them with an SQL Compact database because they depended on stored procedure support for performing their actions. Besides that, clean up and maintenance in general depended on agents which run scheduled clean up tasks.

When Microsoft started working with Web Pages and the WebMatrix, they decided to have another go at this problem. Their first solution was known as universal providers and it solved the problem I’ve mentioned in the previous paragraph (ie, with the universal providers, you can  store your data in a SQL Compact or SQL Azure db) . The easiest way to add the universal providers to your project is to run the following instruction from the Nuget console:

Install-package Microsoft.AspNet.Proviers

Notice that I’ve used plural (provider*s*) because the package ends up installing session, membership, roles and profiles providers. You should also keep in mind that the previous instruction will also update the web.config file so that the app uses all these new providers ( if you’re just interested in one or two, don’t forget to clean up your web.config file).

But the team wasn’t finished yet. They’ve decided to introduce another provider, known as the SimpleMembership, which is way more flexible in its requisites regarding data storage (even though it’s called SimpleMembership provider, the truth is that the package introduces two providers: one for roles and another for membership – this is the most important one). Instead of forcing the use of a specific database table, this provider requires only that you specify the name of the table which is holding your users accounts and the names of the ID and username fields used in that table.

Now, there’s already some resources out there which show you how to get started with this provider (for instance, this one does a good job of explaining what you can expect from it) and that’s why I won’t be wasting your time explaining how it works.

If you’re using Web Pages, you’ll end up getting this provider for free. However, if you’re using Web Forms and you like what you see in that post, then you’re probably wondering about what’s needed to add it to your app. Once again, Nuget is your friend here Smile 

All you need to do to use this provider from your app is to run the following Nuget instruction:

install-package Microsoft.AspNet.WebPages.WebData

Now that you’ve added the required assemblies, I’ll leave it to you to explore the new features introduced by this new provider.

And that’s it for now. Stay tuned for more.

Sep 22

Razor 2: URL resolution improvements

Posted in ASP.NET, MVC       Comments Off on Razor 2: URL resolution improvements

Until now, it was common to see this pattern in our views:

<script src="@Url.Content("~/scripts/myscript.js")"></script>

The Content method is a helper method which is responsible for converting a relative path into an absolute path. From now on (where now is the MVC4 release date which happened sometime ago Smile), we can simplify our code so that it looks like this:

<script src="~/scripts/myscript.js"></script>

Yes, we no longer need to resort to the helper because Razor is smart enough to translate all attribute’s values that start with ~/ into a   @Url.Content call. And when I say *all*, I do mean all. For instance, if the parser finds this:

<div data-info="~/info.txt">Some info</div>

It’s as if you had written this:

<div data-info="@Url.Content("~/info.txt")">Some info</div>

Notice you can also mix values with other code snippets. For instance, suppose you need to build an URL that combines an URL with some variable aux. In that case, you can simply write something like this:

<script src="~/scripts/@aux"></script>

The previous snippet will get translated into the following:

<script src="@Url.Content("~/scripts/")@aux"></script>

Simple, but nice, right? Razor 2 introduces a couple of other interesting features (ex.: conditional attributes), but we’ll leave that for a future post. Stay tuned for more.

Nov 16

I’m still here…really!

Posted in ASP.NET, Books, MVC       Comments Off on I’m still here…really!

It’s been more than one month since I’ve written something in this blog. Unfortunately, I’ve been really busy with work and lots of investigation in several areas…but I think now I’ll be able to return to my daily routines and I’ll try to write at least one post per day Winking smile.

So, what have I been doing lately? Glad you’ve askedSmile I’ve been playing with the latest bits of ASP.NET (Web Forms and MVC). The next release will have some interesting features and that’s why I decided to write a  book about ASP.NET MVC (once again, in Portuguese). This won’t be a big book (like the one about Web Forms), but it will cover all the important details related with MVC projects.

Since my previous experiences have gone really well, I’ve decided once again to ask for the help of the community: if you understand Portuguese and you want to help me improve this book, just drop me a line at labreu I can only have a limited number of reviewers and (unfortunately!) I can only offer a free copy of the book when it’s out for all your hard work Smile

Sep 13

After a bad week (where my work machine died), I’ve finished reinstalling everything. This time, I’ve went with Windows 7 and as a bonus, I’ve ended up with IIS 7.5. One of the things I needed to recover my working environment was to configure access to the certificates’ private keys (I have several WCF services which need certificates). In the old days, the solution was to use the httpcertcfg tool and use the command line.

With IIS 7.5 (also available for IIS running in Vista and Server 2008 with SP2), we’ve got a “new” security feature called application pool identities. According to the docs, application pool identities “allow you to run app pools under a unique account without having to create and manage domains or local accounts”. Until now, everything looks good and this is, indeed, an welcomed new feature. Now, my problem was granting access to the private keys of the certificate to that account. Initially, I’ve tried using my beloved winhttpcertcfg tool:

C:Windowssystem32>winhttpcertcfg -g -c LOCAL_MACHINEMy -s mycertificate -a "IIS APPPOOLASP.NET v4.0"

The result: “Error: no account information found.” Not good. I know that I could use the good old FindPrivateKey utility,but I’ve thought that there should be an easy way of doing these things. And yes,there is. I’ve tripped into an even easier way of granting permissions to a private key (interestingly, available since Windows Vista – note to self: start poking around everywhere when new versions of an OS is released!).  Take a look at the following image:


Notice the Manage private keys entry? Yep, that’s just what the doctor ordered! Clicking over that option ends up showing the security dialog and now it’s only a question of adding the correct account (which, if you’re using the new application pool identity, is as easy as writing “IIS apppoolyour pool name”). Cool, right?

Apr 22

A few days ago I’ve mentioned that my ASP.NET 4.0 book was available for pre-order in the FCA site. It has finally been released during Techdays (Portuguese MS event), so you can order it from the web site or buy it in a book store.

As you can deduce from its title, this book covers ASP.NET 4.0  Web Forms in depth. A warning: don’t be fooled by the number of printed pages! When compared with the previous  3.5 editions, you’ll notice that it has less pages. But that only happened because we’ve (I’ve suggested and the editor agreed) decided to move some of the printed content into online appendixes in order to lower the price of the book. If you look at the contents, then you’ll notice that it covers more stuff than its previous editions (the main difference is that a couple of chapters which were printed are now available for download).

There’s also good news for my Brazilian readers: the book will be distributed in Brazil (and that should mean that its price should not be as high as it used to be in the past). So, if you live in Brazil and you’re interested in buying this book (or one of its previous releases), you should contact Zamboni Comércio de Livros and ask for a copy:

Zamboni Comércio de Livros Ltda.
Av.Parada Pinto, 1476
São Paulo – SP
Telf. / Fax: +55 11 2233-2333

As always, feel free to contact me if you have any questions/suggestions about this book.

Apr 14

It’s still not for sale, but you can be notified when it’s out. Btw, here’s its cover:


Jan 29

The new auto-start feature

Posted in ASP.NET       Comments Off on The new auto-start feature

Version 4.0 of ASP.NET introduces a new feature called auto-start. The idea is simple: to improve the performance of the web app by allowing apps to run some expensive code before the first request comes. I must say that this is really an interesting concept (and no, I won’t be going into details here because the white paper already explains most of what you should know).

I’m only mentioning this here because this will only work from windows 7 and windows 2008 server R2 onwards. This is something which makes me really sad because people running windows 2008 server won’t be able to use this feature. I really believe that it’s time for MS to change the interaction between IIS and the OS…I mean, am I the only one that is fed with having the IIS version tied up with the OS version???

Jan 06

Protected: ASP.NET 4.0: Customizing encoding/decoding

Posted in ASP.NET       Comments Off on Protected: ASP.NET 4.0: Customizing encoding/decoding

This content is password protected. To view it please enter your password below:

Jan 05

[Update: added the missing web.config changed required to make it work]

ASP.NET has been performing some sort of validation on user input for ages. For instance, I guess that most of us know that there is a list of chars which can’t be introduced in a textbox (ex.: <) in order to help protect our pages against vulnerabilities. Now, this validation is lazy and is performed against the data passed through the request (even though the user input validation is the most know validation, it’s also performed against query strings, cookies, etc). Until now, we could only turn this feature on and off by setting the @Page’s ValidateRequest attribute.

The good news is that from ASP.NET 4.0 onwards, this feature is *extensible*. What this means is that we can create our own “validators” for checking the input. If you want to build your own “validator”, you’ll only need to create a new class which extends the RequestValidator class. Then you can override the IsValidRequestString method and writer your own custom validation logic:

public class MyRequestValidatory : RequestValidator {
        protected override bool IsValidRequestString(
            HttpContext context, string value,
            RequestValidationSource requestValidationSource,
            string collectionKey,out int validationFailureIndex ) {
            //some code

As you can see,the method receives several parameters which you can use to perform your logic. As you can probably deduce from its name, the value parameter contains the string that needs to be checked. The RequestValidationSource parameter can be used to determine the kind of HTTP data that has been passed to be validated. The validationFailureIndex should only have a non-negative value when the string passed through value has forbidden chars and it should indicate the position of the string where that invalid char is used. Oh, and I almost forgot: the collectionKey parameter identifies the name of the key in the request collection that is being validated.

After building the “validator”, you need to make ASP.NET use it. The httpRuntime section exposes the requestValidationType attribute which can be used for doing that:

<httpRuntime requestValidationType=" MyRequestValidatory" />

This is another small and “sweet” update to the existing framework. And I guess that’s it for now. Stay tuned for more on ASP.NET.

Jan 04

This is the first post of the year! I guess that means I’ll need to wish you all a fantastic New Year and I really hope that everything you wish comes true!

Now, this is really a short post about two simple new properties that have been added to the Page class: MetaDescription and MetaKeywords. In fact, these are really simple shortcuts for the Description and Keywords properties exposed by the HtmlHead class (oh, btw, you can get access the header by using the Header property exposed by the Page class and this will only return a valid reference when you have a <head> element annotated with a runat=”server” attribute). As you’ve probably guessed, you can use the MetaDescription property to set the “description” <meta> element. On the other hand, you can use the MetaKeywords to set the keywords  <meta> tag.

As I’ve said before, these are really simple additions. But it’s also important to notice that adding simple features which make our lives easier end up contributing to improving the framework, right? And that’s it for today. Keep tuned for more on ASP.NET.

Dec 11

“Finally!!!”, you say…I hear you man! With ASP.NET 4.0, we can enable/disable session state programmatically (like in C# code 🙂 ,,). The new version of the framework adds a new method (SetSessionStateBehavior) to the HttpContext class. You’re supposed to pass it a value from the SessionStatebehavior to influence the use of session state. Currently, you can pass the following values:

  • Default: passing this means that everything works as before (ie, you control session through the @page directive or the <pages> entry in the web.config file);
  • Required: session state is enabled for read/write access;
  • ReadOnly: gives access to read only session state;
  • Disabled: turns off session state for the current request.

In practice, passing one of the last three methods means that eventual settings specified at the @Page directive or in the <pages> element of the config file are ignored. There’s a caveat: you can only use the new method influence the use of state until the AcquireRequestState event is fired. Doing it after means getting an exception.

And that’s it. Stay tuned for more on ASP.NET.

Dec 09

Ensuring that IIS 7 will handle extensionless URLs

Posted in ASP.NET       Comments Off on Ensuring that IIS 7 will handle extensionless URLs

As you probably know, I’ve been updating my ASP.NET book to 4.0. It has been more work that initially expected, but I can also say that I’ve been having some fun. One of the things I’ve had to investigate was routing. This is one of those cool additions that will really help improve SEO in web forms apps (ASP.NET had some support for friendly URLs, but it was close to useless :),,)

Now, if you’ve been doing MVC, you already know that routes are an important feature and you probably know lots about it (btw, I’ve written about it in the past). One of the things you probably know is that getting extensionless URLs in IIS 6 involves some configuration. However, that shouldn’t be needed in IIS 7 and above. I guess it was a surprise to me when I started getting 404 on my demo app for routing in Web Forms. What? 404? But I’m running the site in IIS 7 with integrated mode on…wtf???

Well, after some tweaking, I’ve managed to understand what was going on: you must ensure that the routing module is configured to handle managed and unmanaged requests (there are several options for doing this; the easiest is using the IIS 7 admin console – check the properties of a module and you should see a dialog with a checkbox that lets you enable/disable this feature).

I’ve started asking around and I was lucky enough to get an answer from Stefan Schackow about it. When you create a new VS project, you’ll see that the web.config contains the following entry:

<modules runAllManagedModulesForAllRequests="true" />

this is all that takes to make everything run smoothly. Unfortunately, I’ve ended up deleting that entry from the web.config and that meant that my extensionless URL never got through the URL module (it ended up being processed by the static file handler, which is not a managed handler). Special thanks go to Stefan for helping me with this problem.

Dec 05

The “Cannot open user default database…” error

Posted in ASP.NET       Comments Off on The “Cannot open user default database…” error

Today I’ve ended up getting the following error after refreshing a page that was working (3 minutes before):

Server Error in ”/” Application.

Cannot open user default database. Login failed.
Login failed for user ”IIS APPPOOLASP.NET v4.0”.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: Cannot open user default database. Login failed.
Login failed for user ”IIS APPPOOLASP.NET v4.0”.

As I said, this happened while I was updating the code for my book and it happened when I hit refresh on a working page in the browser. So, if it was working just a few minutes ago, why did it stopped working? It must have been something I’ve done, but what? After some seconds, I’ve remembered that I did add a new LINQ To SQL file to my project and that it used the same SQL Express database (user instance) than the remaining site. After checking the Server Explorer, I could see that VS was still connected to the instance database. And yes, that was the problem: closing the connection on Server Explorer made the error go away!

I’m almost positive that this was not the error one got in previous versions of ASP.NET (when an user instance was opened by some other process), but I might be wrong. Now, the important thing is that if you end up getting this error, you should check if there’s anything holding up your user instance db file. And that’s it. Stay tuned for more.

Dec 03

Everybody knows that using view state means that you’ll go to hell when you die….nonetheless, many keeps using it, even after having been warned about it (probably because they find heaven to dull??? who knows 🙂 ,,)…to be honest, the default opt-out model we had until now didn’t really helped. The good news is that ASP.NET 4.0 introduces a new model known as opt-in model. So, what’s the idea behind it? A quick recap of what we had is in order…until 4.0, view state was controlled through the EnableViewState property. Whenever you set it to false, you’re saying that that control and all its children won’t persist any data in view state.

Now, this caused all sorts of quirks in v1.0 because programmers would turned it off at the page level (less KBs in a page is good, right?) and all hell broke loose because server controls stopped working. The workaround was simple: leave it on by default at the page level and turn it off in all the controls that don’t need it (btw, this was called the opt-out model). Even though ASP.NET 2.0 introduced control state to make controls work without relying on view state, the truth is that existing opt-out view state model still sucked in the real world because 1.) people are lazy and/or 2.) there was always someone who ended up forgetting to disable view state in the controls they’ve added to the page.

Now, things are better with ASP.NET 4.0 and its new opt-in model. In order to make it work, they’ve added a ViewStateMode property, which gets its value from an enum with the same name.Currently, it supports the these values:

  • Inherit: inherits the value of the property from its control parent. This is the default value;
  • Enabled: enables view state in the current control (even if the parent has its ViewStateMode set to Disabled);
  • Disabled: disables view state in the current control.

Before going, you must understand that this property will only be of use when the EnableViewState property is set to true (when it’s set to false, view state is off for that control and all the controls on its control tree). Now, lets see how we can use this new property and the new opt-in model.

By default, ViewStateMode is set to inherit (default value inherited from the Control class itself – which, btw, also sets EnableViewState to true). Now, if you set the ViewStateMode at page level to Disabled, you can turn it on only for the controls that need it by setting that property to enabled on those controls. This is the new (and let me add this: cool!) opt-in model introduced by ASP.NET 4.0.

Final note: If you debug an ASP.NET page, you’ll notice that Inherits is still the value of the ViewStateMode property…if that is the case, then view state shouldn’t be on by default, right? After all, Page is the top control in the control tree and the docs clearly say that view state is on only when the ViewState is set to Enabled or when a parent control has that value and the current one has its mode set to Inherits…so, “what gives?” (reaped shamelessly from October Road, another great TV show which ended abruptly…it seems like these ABC guys terminate all the series I like…oh, lets leave this whining to a future post)

The answer lies on the private SaveAllState method, which is responsible for persisting view state info into the hidden field (the default behavior). When it sees that the ViewStateMode of the page is set to Inherits, it will automatically use Enabled instead. And that’s it. I’ll try to come back with more on ASP.NET.

Nov 26

Protected: Getting 503 errors on IIS 7 with custom application pool (Integrated Mode)?

Posted in ASP.NET       Comments Off on Protected: Getting 503 errors on IIS 7 with custom application pool (Integrated Mode)?

This content is password protected. To view it please enter your password below:

Nov 24

This is a post to my Portuguese readers (ie, for those guys and gals that have read my Portuguese books). I’m still preparing material for a possible ASP.NET 4.0 book and I would really appreciate some feedback on the previous editions (that is, if you read the book). What did you like? What didn’t you like? What would you like to see covered?

If you want, you can put your comments in Portuguese. Thanks for your help.

Nov 06

Crash dumps, ASP.NET and VS 2010

Posted in ASP.NET       Comments Off on Crash dumps, ASP.NET and VS 2010

Pretty cool stuff!

Oct 15

Rick’s tip on ASP.NET client IDs + JQuery

Posted in ASP.NET, Javascript       Comments Off on Rick’s tip on ASP.NET client IDs + JQuery

Rick Strahl has an interesting post on how you might use JQuery’s powerful selector syntax to get a reference to an ASP.NET control placed inside a naming container. Pretty cool stuff :,,)

Sep 13

Dave Reed on MS AJAX 4 preview 5

Posted in ASP.NET, MS AJAX       Comments Off on Dave Reed on MS AJAX 4 preview 5

Another excellent post by Dave Reed on a topic which I shall begin looking at in depth next week.

Aug 24

Protected: Has ASP.NET really left the track?

Posted in ASP.NET       Enter your password to view comments.

This content is password protected. To view it please enter your password below:

Apr 28

MVC Action filter project on Codeplex

Posted in ASP.NET, MVC       Comments Off on MVC Action filter project on Codeplex

Roni Schuetz informed me of a new Codeplex project he created for building a common library of ASP.NET MVC action filters. If you’re into MVC and you’d like to contribute, then check it out.

Apr 13

The MVC framework: the ActionLink control

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the ActionLink control

Ok, so today I’ve finally updated my local copy of the MVC source code (which I’m doing through my preferred SVN client) and lo-and-behold: new stuff to talk about in the MVC futures source code! Today we’re going to talk about the ActionLink control.

As you might expect (from the name), this is a really simple control which extends the base MvcControl. Currently, it exposes the following properties:

  • ActionName: lets you pass the action name that should be used for rendering the link;
  • ControllerName: lets you set the name of the controller. Used for influencing the generated url;
  • RouteName: as you’ve probably guessed, you can use this to generate a link by using its name;
  • Values: lets you pass a dictionary for setting the route’s dictionary values;
  • Text: used for setting the text that is generated for the link.

If you’re used to using the Html.ActionLink helper, then there really shouldn’t be anything new in here. Anyway, here’s an example of how you can use this new control in your page:

<mvc:actionlink runat="server"
     Text="Go to about" />

Unlike the other controls, the name property isn’t really used internally to get any info from the view data dictionary. You’re probably wondering how you can fill the Values property. Nothing better than a quick example…the next snippet creates a link to the Index action and sets its id property (I’m using the default routes you get when you create a new MVC app):

<mvc:actionlink runat="server" ActionName="Index" Text="Go to about" name="message">
  <Values id="1" />

This ends up generating the following HTML:

<a name="message" href="/MvcRTM/home/Index/1">Go to about</a>

If you had more parameters, you could simply add them as attributes to the Value element. And that’s it for today. Stay tuned for more on the MVC framework.

Apr 08

The MVC framework: the AcceptAjaxAttribute

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the AcceptAjaxAttribute

There might be some scenarios where you have methods that should only be invoked for AJAX requests. In those cases, you can use the AcceptAjaxAttribute to decorate those methods. This is an ActionMethodSelectorAttribute which overrides the IsValidForRequest and delegates all its work to the Request.IsAjaxRequest extension method.

When you’re not in an AJAX request, the IsAjaxRequest method returns false and you end up getting a 404 for that call. It’s really a simple attribute and you might want to recall how ActionMethodSelectorAttributes interact with the remaining elements of the platform.

And that’s all there is to say about this attribute. Stay tuned for more on the MVC framework.

Apr 07

The MVC framework: setting a timeout

Posted in ASP.NET, MVC       Comments Off on The MVC framework: setting a timeout

In the last posts, we’ve taken a look at how we can add asynchronous action to a controller. Today, we’re going to dig a little deeper and see how we can specify a timeout that limits the maximum amount of time that the asynchronous operations can take to complete.

By default, you inherit a default timeout: all actions must complete under 30 seconds (as you can see, if you peek into the AsyncManager class). You can specify the timeout in two ways: by interacting directly with the AsyncManager’s Timeout property or by using one of the existing timeout attributes.

If you want to use an attribute, then you can simply decorate a method (or a controller class) with the AsyncTimeoutAttribute. This is an action filter attribute which receives an integer that defines the valid timeout for the current asynchronous request. If you don’t want to limit the asynchronously execution in time, then you can simply pass Timeout.Infinite(–1) to the constructor. Alternatively, you can also annotate the method/controller with the NoAsyncTimeoutAttribute (this attribute expands the previous one and passes Timeout.Infinite to its constructor).

And that’s all for today. Keep tuned for more on the MVC framework.

Apr 06

Protected: The MVC framework: the RequireSslAttribute

Posted in ASP.NET, MVC       Enter your password to view comments.

This content is password protected. To view it please enter your password below:

Apr 05

This is the last post in the asynchronous action pattern series. In this post, we’re going to present the (so called) “delegate” pattern. This is really similar to the “event” pattern. The difference is that, in this case, we return a parameterless delegate from our begin method which will be called when all the asynchronous operations end.

To illustrate this pattern, we’re going to update the previous example. Here’s the final code:

public Func<ActionResult> GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET";
  AsyncManager.RegisterTask(cb => req.BeginGetResponse(cb, null),
     ar => {
               var response = req.EndGetResponse(ar);
               using (var reader =
                      new StreamReader(response.GetResponseStream())) {
                  ViewData["contents"] = reader.ReadToEnd();

return () => View(“Index”);

When compared with the “event” pattern, you can quickly see that:

  • the begin method returns a parameterless delegate which will be called when all the asynchronous operations end;
  • since we can’t pass any parameters to our custom callback method, we write the HTML directly to the ViewData dictionary;
  • we use a Lambda expression since the view we’re rendering doesn’t have the same name as the action method (if that was the case, we could simply return a reference to the View method, ie, we could simply write return View;).

And that’s all for today. More about the MVC framework on the next posts. Keep tuned!

Apr 05

The MVC framework: simplifying the “event” pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: simplifying the “event” pattern

In the previous post, we’ve taken a look at the “event” pattern. In this post, we’re going to see how we can simplify the needed code for using this pattern. The AsyncManager exposes a RegisterTask method which simplifies the needed code when we decide to use this pattern. We’ll improve the previous example by using this method. Here’s the code:

public void GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET"; 
  AsyncManager.RegisterTask(cb => req.BeginGetResponse(cb, null),
    ar => {
               var response = req.EndGetResponse(ar);
               using (var reader =
                         new StreamReader(response.GetResponseStream())) {
                  AsyncManager.Parameters["contents"] = reader.ReadToEnd();


public ActionResult GetHtmlCompleted(String contents) {
  ViewData["contents"] = contents;
  return View("Index");

As you can see, the code is really similar to the one we’ve shown in the other post. The main difference is that with this helper method you’ll only need to worry with setting up the asynchronous action.

And that’s all for today. On the next post, we’ll talk about the latest option for having asynchronous actions in MVC controllers.

Apr 05

The MVC framework: the “event” pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the “event” pattern

Today we’re going to keep looking at the MVC framework and we’ll see how we can use the “event” pattern for invoking an action asynchronously. This pattern is really simple. You start by adding two methods: the first is responsible for kicking off the asynchronous processing and the second will be called when all the asynchronous actions complete (as you’ll see, with this approach you can start several asynchronous actions). The ending method’s name should follow a specific convention: it must end with the word Completed (where XXX is the name of the action method that is exposed by your controller) and it should return the ActionResult object responsible for kicking off the view rendering phase.

When you opt for this approach, you’ll have to notify the framework whenever you start an asynchronous task (and you also need to signal its end). In practice, this means that you’ll have to increment the AsyncManager’s OutsandingOperations property whenever you start an asynchronous action. And then you’ll also have to decrement this property when that async operation is completes. Internally, this property delegates to a counter and when that counter reaches 0, the platform will automatically invoke your XXXCompleted method.

Your XXXCompleted method might also receive parameters that are automatically fed with the values that might have been added to the AsyncManager’s Parameters property. In practice, when the platform invokes the XXXCompleted method, it will try to match the expected XXXCompleted parameters with values that might exists on the AsyncManager’s Parameters property. Those parameters which don’t exist in that Parameters property get their default value (default(T)).

The restrictions presented for the IAsyncResult pattern applies to this option too. That means that filters must be applied to the begin method (and not to the end method) and that the end method must match the real method name (instead of an eventual alias name that might have been applied to that method). Enough theory…it’s time to show some code. We’re going to reuse the previous example and change it so that we apply this pattern:

public void GetHtml(String url) {
  var req = WebRequest.Create(url);
  req.Method = "GET";
                (ar) =>
                    var response = req.EndGetResponse(ar);
                    using (var reader = new StreamReader(response.GetResponseStream())) {
                        AsyncManager.Parameters["contents"] = reader.ReadToEnd();

public ActionResult GetHtmlCompleted(String contents) {
  ViewData["contents"] = contents;
  return View("Index");

There are a couple of interesting observations that you can take from this example:

  • we increment the OustandingOperations before kicking the asynchronous operation;
  • at the end of the callback method, we decrement the OutstandingOperations. When it reaches 0, the GetHtmlCompleted method is called;
  • notice that we use the Parameters property to set the contents parameter value. btw, if we wanted we could also add an entry to the ViewData dictionary instead of doing that in the XXXCompleted method.

Even though the sample has only kicked off one asynchronous operation,nothing prevents you from starting several asynchronous operations. The only thing you can’t forget to do is to keep track of the current running asynchronous operations by incrementing and decrementing the OutstandingOperations property.

And that’s it for today. More about asynchronous

Apr 02

The MVC framework: the IAsyncResult pattern

Posted in ASP.NET, MVC       Comments Off on The MVC framework: the IAsyncResult pattern

In this post we’re going to keep looking at the asynchronous features introduced by the MVC futures and we’ll see an example of how to use the IAsyncResult pattern for adding an asynchronous action to a controller. The idea is simple: you need to add two methods with the following signatures:

public IAsyncResult BeginActionMethod(Int32 id, AsyncCallback callback, Object state);
public ActionResult EndActionMethod(IAsyncResult asyncResult);

This is the expected asynchronous version of the traditional synchronous methods you generally end up using on the ASP.NET MVC applications. To illustrate its use, we’re going to change the default HomeController you get when you create a new ASP.NET MVC project and add a new method which gets the HTML returned from an existing url. Lets start with the changes we’ll be doing to the Index view:

% using( var frm = Html.BeginForm( "GetHtml", "Home") )
  <label for="url">Url: </label>
  <input type="submit" value="Get html" />

Nothing new here: just a simple form which submits itself to a GetHtml action method on the Home controller. Now, the interesting part. Here’s the code we’ve added to the controller:

public IAsyncResult BeginGetHtml(String url, AsyncCallback cb, Object state)  {
  var req = WebRequest.Create(url,,);
  req.Method = "GET"; 
  return req.BeginGetResponse(cb, req);

public ActionResult EndGetHtml(IAsyncResult ar) {
  var req = ar.AsyncState as WebRequest;
  var response = req.EndGetResponse(ar);
  using (var reader = new StreamReader( response.GetResponseStream() ) ) {
     ViewData["contents"] = reader.ReadToEnd();
  return View( "Index" );

The most interesting thing is that the method signature can be slightly changed so that you get all the goodies you’re used to in the synchronous model (ie, you can still have automatic binding between the method’s parameters and the form’s submitted values).

As you can see, we’re returning the IAsyncResult object that resulted from the call to the BeginGetResponse method (notice also the chain of callbacks in the BeginGetHtml method: we don’t pass our callback method to it; instead, we’re passing the callback method that we’ve received in our method – parameter cb). The EndGetHtml method is also pretty simple: we’re just getting the response and translating it into a string. Finally, we return the ActionResult that will render our view. btw, you should also add something like this to the Index view:

<%= Html.Encode(ViewData["contents"]  ) %>

This ensures that you’ll see the return HTML on your view.

There are some things you should keep in mind when using this approach:

  • filter attributes must be placed in the begin method;
  • even though you can apply the ActionNameAttribute to the BeginXXX method, the End method must match the real method name (and not the alias you’ve created by using the ActionNameAttribute);
  • You can’t call Begin methods directly when using asynchronous controllers. If you need that, you’ll have to use the previous attribute (ActionNameAttribute) to create that illusion.

And that’s all for today…more on asynchronous calls in the next posts. Keep tuned.