First time here? You are looking at the most recent posts. You may also want to check out older archives or the tag cloud. Please leave a comment, ask a question and consider subscribing to the latest posts via RSS. Thank you for visiting! (hide this)

April 2009 Blog Posts

Free Chapter of Beginning ASP.NET MVC 1.0 – Testing ASP.NET MVC Applications

BeginningASPNETMVCv1 It is with an unquantifiable amount of pleasure that I can announce that we have just released a free public preview chapter of our Beginning ASP.NET MVC v1.0.

The name of the chapter is “Chapter 9 – Testing ASP.NET MVC Applications”.

It explains how to test controllers, how to use mocking to test interactions with the Http runtime, how to refactor an application to make it testable, and also shows some TDD in action.

Also, when you read it, remember that the intended audience is developers that are new to ASP.NET MVC and most likely also novice to testing, mocking and all that stuff (to address that Chapter 8 is an introduction to unit testing).

But without further ado, here is the link to get the free chapter Testing ASP.NET MVC Applications taken from our book Beginning ASP.NET MVC 1.0.

Remember that the usual warnings apply: it’s still a preview, additional editing and proofreading will be done, the layout is not final and still include directive for production.

Please, download it, read it, and let us know what you think of it (we’ll be monitoring the forum and answering to questions).

And while we are on the topic, since many people asked this, the book is almost complete, just a few steps of the long process need to be done and we expect the book to be available in bookstores (and on Amazon) at the beginning of August (a bit more than one year since we started writing the book)

kick it on DotNetKicks.com

Technorati Tags: ,,

PS: The first person plural you read in the post (we, our) is not because I suffer of a disjoint personality, but because the book is co-authored by Keyvan and I.

ASP.NET MVC brings FUN back inside web development, on .NET

That’s the main fact about ASP.NET MVC:

“ASP.NET MVC brings the web back inside web development”
[from a tweet by Hadi Hariri]

With ASP.NET MVC the “real” web is back into the development workflow of a web application. And to me this translates in having more fun developing apps, and, at the end of the day, being more productive since I don’t have to work-around issues of a framework that takes too much of my work.

It’s true: some might say that ASP.NET MVC is “half-backed” or without a strong opinion about how the M should be implemented, and that there is a lot of infrastructural code to write. But to me, being able to granularly control my HTML, the way I persist the state of the application is a much bigger point in favor of ASP.NET MVC.

Jeffery Palermo wrote a post saying that you should NOT use ASP.NET if you don’t know about object-orientation, you are not willing to build on top of the framework, if you are adverse to open-source and if you rely on 3rd party controls vendors.

I add: you should NOT use ASP.NET MVC if you are not willing to gets your hands dirty with the basic languages of web: HTML, CSS, JavaScript.

There is an ongoing discussion on why web developers use PHP/RoR instead of ASP.NET: my personal opinion is that this happens because ASP.NET WebForms hides the web from the developer, and web developers want to “play” with the web. With ASP.NET MVC, if marketed correctly by Microsoft, this situation might improve.

kick it on DotNetKicks.com

Technorati Tags: ,,,

The real headquarters of Oracle


deathstar.jpg

<rant mode="on">

Oracle buys Sun and, incidentally, gets MySql and "might" put an end to it.

A few days before that, the NY jury says that the new America's Cup, as planned by Alinghi is invalid (which was challenged by a yacht club which didn't have the pre-requisites to start an AC challenge), and so they are forced to accept the challenge made by Oracle Racing two years ago, which challenged them to race on 90x90 feet multi-hulls (for non US people, around 27m x 27m).

Later, Ellison, in compliance with his egocentric view of the World, sends a letter to Alinghi "suggesting" a new format for the competition and proposing to jointly manage the next America's Cup. This is the first time in 150 years that the challenger proposes to manage the competition: it's the defenders that does this.

So, Alinghi refuses the new "suggestions" and accepted the multi-hull competition.

Is Ellison, the man who thinks that the only difference between him and God is that God don't think He is Larry Ellison, working in a secret moon sized battle station? I mean... MS is not a charity, but at least Bill Gates is not that mean.

</rant>

Sorry for the rant... but I had to write this... I'm so angry at Oracle for how they managed to (or are trying to) destroy the America's Cup as we knew it. Not that this never happened before, but...

Thanks to Eric Williams for the inspiration

Stopping the panic: how to improve HtmlHelper.RenderPartial performances. Don’t run in debug mode

There has a been a lot of talking on a possible “big design flaw” in ASP.NET MVC: partial view path resolution was not cached and so a big performance issue. It all started with Rudi Benkovic’s presentation on ASP.NET MVC performances.

I also wrote a commentary on his presentation, but I was a bit skeptical about the fact that view path resolution was faster with a full url than with just the name of the view. I said:

This last one looks strange to me because the RenderPartial method should be caching the path resolution: maybe it’s a bug, or the test was performed with a pre-release version that didn’t cache the result.

But I didn’t have time to really test the behavior.

Then today another post came out: ASP.NET MVC: Hidden Performance Problem with HtmlHelper.RenderPartial functions.

He says that for each view rendered, all the search path are probed and, in order to understand whether a file exists or not, they throw an exception. This sounds silly to me, so this evening I decided to try it myself.

And I found the way to improve the performances without adding another layer of cache as someone was already planning to. Just don’t run in debug mode:

<compilation debug="false">

Yes, it’s that simple.

Since ASP.NET MVC source code is public (actually it’s OpenSource) I had a look at it. And I found out the following line:

protected VirtualPathProviderViewEngine() {
    if (HttpContext.Current == null || HttpContext.Current.IsDebuggingEnabled) {
        ViewLocationCache = DefaultViewLocationCache.Null;
    }
    else {
        ViewLocationCache = new DefaultViewLocationCache();
    }
}

This says: if you are in debug mode (or are not in a web environment, like in tests), don’t cache. Otherwise use the cache.

I also went a bit on, and added some logging inside the view path resolution, in order to run it in release mode and see with my eyes that the cache was being used. The code that follows is the GetPath method inside the VirtualPathProviderViewEngine.cs file (code truncated to enhance readability):

private string GetPath( /* truncated */) {

     /* truncated */

      if (useCache) {
        string result = ViewLocationCache.GetViewLocation(
                                          controllerContext.HttpContext, cacheKey);
        if (result != null) {
            controllerContext.HttpContext.Response.Write(
                      String.Format("{0} lookup returned {1}\r\n", name, result));
            return result;
        }
    }

    controllerContext.HttpContext.Response.Write(
                String.Format("{0} lookup no cache\r\n", name));
    return (nameRepresentsPath) ?
        GetPathFromSpecificName(/* truncated */) :
        GetPathFromGeneralName(/* truncated */);
}

If you run in debug mode you will always see, when calling the RenderPartial on the LogOnUserControl, “LogOnUserControl lookup no cache”. But if you run it in release mode, you will get the no cache message the first time you run it, and later you’ll get “LogOnUserControl lookup returned ~/Views/Shared/LogOnUserControl.ascx”.

So, problem solved, no “big error” inside ASP.NET MVC 1.0, just someone that forgot the set the debug flag to false when doing its performance testing. And innocently spread the panic around that.

Actually finding that they decided to use no cache in debug mode was difficult to discover without looking at the code, but when you do tests, especially performance test, remember to run in release mode.

There are also other reasons why you don’t want to run production or performance testing code in debug mode. Read what Tess has to say about that: ASP.NET Memory: If your application is in production… then why is debug=true

kick it on DotNetKicks.com

Technorati Tags: ,

Roma gets its local user group as well

Probably it was the last big area of Italy with IT companies without a .NET User group. But around one month ago Emanuele Mattei and a few other developers from the “Urbe” fixed this problem and founded DotNetRomaCestà.

logo_dotnetromacesta

A big welcome to the 7th .NET Regional Italian UserGroup born in the last few years.

A small note on the name: it means “in Roma there is dotNet” (“ce stà” means, in Roman dialect, “there is”).

Looking forward to see what they are going to organize.

Good look!

Technorati Tags: ,

Italian ALT.NET Summer Conference: vote the sessions

June 27th is the date for the next Italian ALT.NET conference. And for the first time in Italy in a .NET UserGroup the sessions have all been proposed by the members of the user group. And since we received 18 proposal out of only 5 time slots, last week we also started the public voting.

If you are planning to attend to the conference, please join the group, and go voting.

Among the many proposals and think that a few require a special mention:

But there is more than just these 5 ones: you can read about the others on the ugialt.net website: http://ugialt.net/IV_UgiAltNetConf.ashx (here translated in English)

Why did we decide to do a call for presenters and then open the public voting: because we wanted to give a voice to the many developers out there that had never had a chance to present at a user group meeting. Given the big response we had, the next conference will probably have more than one room, so that we will have even more people talking about interesting topics.

If you are planning to come, and you didn’t vote already, do it now!

Technorati Tags: ,

The performance implications of the expression tree-based ActionLink helper

Earlier today I wrote a post about how to improve the performance of ASP.NET MVC web applications, and I came out with the conclusion that the best way to improve performance is to add data caching and that the rest was not very important.

Rudi sent me an email pointing out that turning the optimization upside down as I asked in my post, the expression tree-based ActionLink method still causes a lot of performance problems, at least in his sample application, a DIGG-like application, where there are 4 calls to the ActionLink helper for each of the 20 items displayed on the page plus some other calls around the page (from a slide of the presentation, it seems like the sample calls the method at least 160 times per page).

So I decided to analyze the results of his performance test better, and it really turns out that, in his context, with hundreds of calls to the ActionLink method, this method is a big performance issue.

Go and have a look at the original presentation, on page 26, to read the reasons why it is so slow.

What are the data really saying?

I based my previous assumptions on the number of requests per second gained, but I missed one important factor: relative gain. Gaining 10 requests with a baseline of 6 is a much better improvement than gaining 25 on a baseline of 60.

So I created that graphs that help visualize the real relative gain:

PercentualGain

The best relative improvement still happens with data caching (a 427% gain), but the second one (150% gain) is using the RouteLink helper specifying the RouteName instead of the lambda expression-based ActionLink helper. The third one is again something related to data (using compiled LINQ queries, with a 94% gain) and then another ASP.NET MVC related issue: specifying the full path to a view is 63% faster (in his scenario where partial views are called 41 times per view) then specifying the view name only. This last one looks strange to me because the RenderPartial method should be caching the path resolution: maybe it’s a bug, or the test was performed with a pre-release version that didn’t cache the result.

UPDATE: Rudi tested everything with the beta version, and since then the WebFormViewEngine caches the resolution of view paths. Furthermore also running in debug mode disables the caching. So this is not a performance issue. Read more about this on my follow-up post: Stopping the panic: how to improve HtmlHelper.RenderPartial performances. Don’t run in debug mode

Analyzing one of the other two graphs would have lead to the wrong conclusion: the req/sec was emphasizing the gain provided by the data caching too much, and the time per request emphasizes too much the gain caused by not using the expression tree based method:

ReqPerSecGain TimePerRequestGain

What do we get from this?

Number 1 - a correct data visualization is the key to understanding the problems better.

Number 2 – Data caching is still the most effective way to improve the performance of a data driven application.

Number 3 - the expression tree based ActionLink helper has some performance problems.

Number 4 - if the test was performed on the RTM, there is a bug in the caching of view path resolution.

What can you do to to help your performance?

Implementing a route resolution cache, might boost the performance of all the url generation story, and I think that this is something Microsoft should look at for a next version of the routing engine.

How to improve the performance of ASP.NET MVC web applications

Today I stumbled upon a nice presentation that Rudi Benkovic gave last week at the Slovenian DotNet User Group, about ASP.NET MVC Performance.

The Big Picture

It is an in depth analysis of a Digg-like site and how it went from serving (on a test machine) 6 req/sec to 390 req/sec.

The biggest gain, 74 req/sec to 390 req/sec happened when he introduced data caching and another 25 req/sec where gained when he introduced the compilation of LINQ queries.

Data caching is always the key

Splitting the gains among the various components:

  • 29 req/sec optimizing the usage of ASP.NET MVC (I’ll come to this later)
  • 14 req/sec caching route resolution
  • 340 req/sec caching the data access layer

This proves that, no matter what you do to optimize your code, the biggest performance hit is data retrieval, and the first thing you have to optimize is always this.

[UPDATE: I wrote another post with a better analysis of data]

The original presentation also have some nice graphs, so I recommend you go and watch it.

Can ASP.NET MVC be still optimized a bit?

But apart from this obvious outcome, I just want to take out from this presentation the 3 point that are really specific to ASP.NET MVC.

Route resolution

9 request per second are gained optimizing the route resolution. There are a lot of ways to do route resolution (aka creating a link given the action/controller you want to link to), but they can be summarized with these 3:

  • expression tree-based ActionLink
  • string-based ActionLink
  • RouteLink specifying the RouteName
  • (there is also the 4th one, the hard-coded one, but I’d rather not take this into account)

From the presentation it comes out that the first way, the expression tree one, is 30 times slower than the string-based version, which takes twice the time of specifying directly the RouteName.

So, not only the expression tree-based ActionLink is “deprecated” as it doesn’t work for action whose name has been changed through the ActionName attribute, but it’s also slower. We are talking about 1.95 ms versus 0.06 ms, and this can be considered as premature optimization (a 2ms improvement in a request that takes 200ms), but if your views have hundreds of these expression tree-based link, this can become a performance problem, as it is for the sample application analyzed which has more than hundreds of ActionLinks in the page.

Also consider that this is the first optimization he did, and with this he passed from 6 to 15 requests per second, which is a more than 150% gain. So, a pretty big gain here. You can read more about how this method is a problem on the follow up post: The performance implications of the expression tree-based ActionLink helper

Caching Route Resolution

Routes are resolved lots of time during the application lifetime, so caching them could be a nice solution: in the performance test Rudi said that this made him gain 15 req/sec. Again, not a big gain, but since implementing that kind of route resolution caching should not be a difficult task, probably it can be worth writing a small UrlHelper that caches the routes already resolved. Actually, this could be something Microsoft could add to routing engine itself.

Optimize the usage of PartialViews

In the benchmark application, the code does a loop over a list of items, and for each item it calls a RenderPartial to display the detail of each item of the list. In his benchmark the same partial was called 41 times per request.

So he decided to place the for-each loop inside the Partial View, and so have kind of the same encapsulation of markup, but gaining another 10 req/sec. This way you cannot see at a first glace that there is for-loop going on inside the partial, so probably a better solution could have been an Html Helper. Or something that the pre-compiler could have done was to “inline” the loop.

With this I don’t to say that you have to inline everything, but just remember that every RenderPartial you call has a performance hit.

Path to PartialViews

Finally he said he gained another 10 req/sec optimizing how the path to the partial views is specified. You can either specify the view path as only its name (and so the view engine will go and look for it in the current folder or in the shared folder) or you can specify the full path. But if I’m not wrong, the resolution of the real path given the name of the view is cached, so the gain is only achieved in the really first call to the method, and would have probably been averaged out if the benchmark was run for a longer time.

UPDATE: Rudi forgot to set the debug flag to false, thus disabling the view resolution caching. And when running in production you always have to set debug to false. So this is not a performance issue. Read more about this on my follow-up post: Stopping the panic: how to improve HtmlHelper.RenderPartial performances. Don’t run in debug mode

Key takeaways

What do we have to learn from this performance analysis?

First and foremost, that data caching is the easiest and most effective way to improve the performance of your applications: without this, every other optimization is a “micro-optimization”.

If then we really want to get some other rules to apply to ASP.NET MVC applications here they are:

  1. Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
  2. Consider implementing a route resolution caching strategy (and waiting for MS to include something similar in a future version of System.Web.Routing)
  3. Use your common sense when you put RenderPartials on your views page: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that.

But, again, before fine-tuning these aspects of ASP.NET MVC, remember that your data access has to be cached in some way. If you don’t do to that, everything else is just a waste of time.

I ask Rudi if he could first apply the caching of data only, and then apply all the other optimizations, and see which is the impact of the ASP.NET MVC specific optimizations.

What are your ideas on this? Do you think that there are other ways of optimizing ASP.NET MVC that are not micro-optimizations? Please share your thoughts leaving a comment.

kick it on DotNetKicks.com

The Lounge Survey

The Lounge, the advertising network I’m part of, is running a survey in order to understand better the readers who visit the blogs of the network.

At the end of the survey, two random entries will win all the 41 books of the Manning In Action series, and the results will be made public.

Go and take the survey now.

Technorati Tags: ,

I’m an ASP Insider

image

I just learnt that I’ve be invited to join the ASPInsiders. I’m really excited and honored to be part of this group of great ASP.NET experts. Looking forward to help with my feedbacks the ASP.NET team build a better web application framework on the .NET platform, especially in the area of ASP.NET MVC.

If don’t know who they are, here is a quick “elevator speech”, taken from the site:

“The ASPInsiders is a select group of international professionals who have demonstrated expertise in ASP.NET technologies and who provide valuable, early feedback on related developing technologies and publications to their peers, the Microsoft ASP.NET team and others.”

And if you want to know more about this program, who they we are, how the group is organized and how new members are selected I really recommend you read the following post by Rob Chartier: Who are the ASPInsiders?

Now time to learn the *secret handshake*.

Technorati Tags: ,,

Simone Chiaretta cartoon style

Stephen Price, Silverlight guy by day and cartoonist/caricaturist by night, just drawn a nice caricature of me.

Have a look at the original post by Stephen, and all the other caricatures he made.

And, Happy Easter to everyone

13 ASP.NET MVC extensibility points you have to know

One of the main design principles ASP.NET MVC has been designed with is extensibility. Everything (or most of) in the processing pipeline is replaceable so, if you don’t like the conventions (or lack of them) that ASP.NET MVC uses, you can create your own services to support your conventions and inject them into the main pipeline.

In this post I’m going to show 13 extensibility points that every ASP.NET MVC developer should know, starting from the beginning of the pipeline and going forward till the rendering of the view.

1. RouteConstraint

Usually you could put some constrains on url parameters using regular expressions, but if your constrains depend on something that is not only about the single parameter, you can implement the IRouteConstrains’s method and put your validation logic in it.

One example of this is the validation of a date: imagine an url that has year, month and date on different url tokens, and you want to be able to validate that the three parts make a valid date.

2. RouteHandler

Not really specific to ASP.NET MVC, the RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm.

3. ControllerFactory

The controller factory is the component that, based on the route, chooses which controller to instantiate and instantiate it. The default factory looks for anything that implements IController and whose name ends with Controller, and than create an instance of it through reflection, using the parameter-less constructor.

But if you want to use Dependency Injection you cannot use it, and you have to use a IoC aware controller factory: there are already controller factory for most of the IoC containers. You can find them in MvcContrib or having a look at the Ninject Controller Factory.

4. ActionInvoker

ActionInvoker is responsible for invoking the action based on it’s name. The default action invoker looks for the action based on the method name, the action name and possibly other selector attributes. Then it invokes the action method together with any filter defined  and finally it executes the action result.

If you read carefully you probably understood that most of the execution pipeline is inside the logic of the default ControllerActionInvoker class. So if you want to change any of these conventions, from the action method’s selection logic, to the way http parameters are mapped to action parameters, to the way filters are chosen and executed, you have to extend that class and override the method you want to change.

A good example of this, is the NinjectActionInvoker I developed to allow injection of dependencies inside filters.

5. ActionMethodSelectorAttribute

Actions, with the default action invoker, are selected based on their name, but you can finer tune the selection of actions implementing your own Method Selector. The framework already comes with the AcceptVerbs attribute that allows you to specify to which HTTP Verb an action has to respond to.

A possible scenario for a custom selector attribute is if you want to choose one action or another based on languages supported by the browser or based on the type of browser, for example whether it is a mobile browser or a desktop browser.

6. AuthorizationFilter

These kind of filters are executed before the action is executed, and their role is to make sure the request is “valid”.

There are already a few Authorization filters inside the framework, the most “famous” of which is the Authorize attribute that checks whether the current user is allowed to execute the action. Another is the the ValidateAntiForgeryToken that prevents CSRF attacks. If you want to implement your own authorization schema, the interface you have to implement is IAuthorizationFilter. An example could be the hour of the day.

7. ActionFilter

Action Filters are executed before and after an action is executed. One of the core filters is the OutputCache filter, but you can find many other usages for this filter. This is the most likely extension point you are going to use, as, IMHO, it’s critical to a good componentization of views: the controller only has to do its main stuff, and all the other data needed by the view must be retrieved from inside action filters.

8. ModelBinder

The default model binder maps HTTP parameters to action method parameters using their names: a http parameter named user.address.city will be mapped to the City property of the Address object that itself is a property of the method parameter named user. The DefaultModelBinder works also with arrays, and other list types.

But it can be pushed even further: for example you might use it to convert the id of the person directly to the Person object looking up on the database. This approach is explained better in the following post Timothy Khouri (aka SingingEels): Model Binders in ASP.NET MVC. The code is based on the preview 5, but the concept remains the same.

9. ControllerBase

All controllers inherit from the base class Controller. A good way to encapsulate logic or conventions inside your actions is to create you own layer supertype and have all your controllers to inherit from it.

10. ResultFilter

Like the ActionFiters, the ResultFilters are execute before and after the ActionResult is executed. Again, the OutputCache filter is an example of a ResultFilter. The usual example that is done to explain this filter is logging. If you want to log that a page has been returned to the user, you can write a custom RenderFilter that logs after the ActionResult has been executed.

11. ActionResult

ASP.NET MVC comes with many different kind of results to render views, to render JSON, plain text, files and to redirect to other actions. But if you need some different kind of result you can write your own ActionResult and implement the ExecuteResult method. For example, if you want to send a PDF file as result you could write your own ActionResult that use a PDF library to generate the PDF. Another possible scenario is the RSS feed: read more about how to write a RssResult in this post.

Look at implementing a custom action result when the only peculiarity is how the result is returned to the user.

12. ViewEngine

Probably you are not going to write your own view engine, but there are a few that you might consider using instead of the default WebForm view engine. The most interesting one, IMHO, is Spark.

But if you really want to write your own view engine, have a look at this post by Brad Wilson: Partial Rendering & View Engines in ASP.NET MVC

13. HtmlHelper

Views must be very dumb and thin, and they should only have html markup and calls to HtmlHelpers. There should be no code inside the views, so helpers come very handy for extracting the code from the view and putting it into something that is testable. As Rob Conery says: “If there's an IF, make a Helper”.

What is an HtmlHelper? Basically it’s just an extension method of the HtmlHelper class, but that’s the only requirement.

You can read more about how HtmlHelpers are a great way to encapsulate code for view on Rob’s post: Avoiding Tag Soup.

Which one should you use in your applications?

As you might have guess, not all the application you write need you to extend the framework in all the 13 extension points above. The ones the are most likely needed in every applications are ActionFilters and HtmlHelpers. Then you might probably want to use extensions someone else wrote, like an alternative ControllerFactory to use a IoC container or ViewEngine to get rid of the WebForm taste.

But, it’s important to experiment on these extension points so that you know which are your options and you are ready to exploit their power when needed. In the next weeks I’m going to write a few posts on how some of these extension points can be used.

And if you want to read that topics covered more in detail you might consider buying one of the many books that are coming out about ASP.NET MVC, like, “Beginning ASP.NET MVC” (which I happen to be the author) or “Professional ASP.NET MVC” (written by the team that wrote the framework itself) or “ASP.NET MVC in Action” (by Jeffrey Palermo and Ben Scheirman)

Did I miss some extension point you think it’s important to use? Did you use any of the extension points I listed above? I’d love to hear from you which scenario you addressed.

kick it on DotNetKicks.com

One little gotcha to remember when upgrading to ASP.NET MVC RTM

Currently I’m in the process of upgrading all the samples I wrote from my Beginning ASP.NET MVC 1.0 book from the Beta to the RTM version of ASP.NET MVC. The biggest update is taking advantage of the views without code-behind. This is not something you have to do on a “real application” since the old way will work also on the RTM, but since my samples are made to show how to develop an ASP.NET MVC application, I hade to upgrade them all to the “correct” way of doing things.

The first step is pretty easy: just download the .cs and .designer.cs files that are nested behind the view.

Then you have to change the View Page directive removing the CodeBehind attribute and changing the Inherit one to System.Web.Mvc.ViewPage.

<%@ Page
    Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    AutoEventWireup="true"
    CodeBehind="Index.aspx.cs"
    Inherits="SampleApp.Views.Home.Index" %>

The code above must be changed to:

<%@ Page
    Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage" %>

And everything works great with loosely typed views.

If you have to upgrade a strongly typed view, you have to change the Inherits attribute to the generic version of ViewPage (and don’t forget to import the namespace where the presentation model object is).

<%@ Page
    Language="C#"
    MasterPageFile="~/Views/Shared/Site.Master"
    Inherits="System.Web.Mvc.ViewPage<MyDto>" %>
<%@ Import Namespace="SampleApp.Models"%>

But if you run the page you get the following error:

Could not load type 'System.Web.Mvc.ViewPage<MyDto>.

This is because the ASP.NET compiler cannot understand the generic syntax with angle brackets, but only the ugly backtick one (ViewPage`1[MyDto]).

It took me a while to understand how to solve the problem, and I ended up making an app from scratch and comparing the two folders. To make this work you have to add, in the web.config file that is inside the Views folders, the following section (actually, replacing the one that is there already, text wrapped to enhance readability):

<pages
    validateRequest="false"
    pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc,
        Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=1.0.0.0,
        Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc,
        Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <controls>
    <add assembly="System.Web.Mvc, Version=1.0.0.0, Culture=neutral,
        PublicKeyToken=31BF3856AD364E35"
        namespace="System.Web.Mvc" tagPrefix="mvc" />
  </controls>
</pages>

This tells the ASP.NET compiler to use the ASP.NET MVC specific parse filter that understands the angle bracket syntax.

HTH

Technorati Tags:

Reminder: my talk at DotNetUmbria

Just a quick reminder, tomorrow afternoon I’ll be talking about ASP.NET MVC at the local DotNetUmbria usergroup.

Today I spent the whole day putting the finishing touches on tomorrow’s talks and demos. I’ll talk from 3PM to 6PM (or till when people ask for mercy). I’ve two talks planned:

  • Introduction to ASP.NET MVC, my “usual” introductory presentation, update with the RTM bits and yesterday’s big announcement
  • ASP.NET MVC, so what? This was originally planned to be a “live refactoring” of an old WebForm application to ASP.NET MVC, but I changed it for mainly one reason: I realized that to show the issues of migrating I would have need a WebForm application made on purpose to show the problems, and migrating a “normal” application would have not been such a good thing.

So I decided I’ll talk about some of pain-points of ASP.NET MVC and how they can be solved.

My second talk will be about the following topics (or just some if time goes short):

  • ASP.NET MVC vc ASP.NET WebForm
  • Testing with Http* mocking
  • How to use DI/IoC inside ASP.NET MVC (with Ninject)
  • Validation
  • Components and partials
  • Ajax – jQuery
  • DataGrid MVC version
  • PRG Pattern
  • ASP.NET Futures
  • T4

For those who cannot attend I’ll upload the slides (after having translated them to English) and the demos.

See you there, and don’t forget the Sagrantino party in honor of ASP.NET MVC going OpenSource. And the usual Wrox book random draw.

BTW: the event is sold out, but if you want to come and you did not register, I’m pretty sure we’ll find a way to let you in.

Technorati Tags: ,,

April’s fool or not? ASP.NET MVC source released under MS-PL

garland_logo I’m still not convinced completely (the news was announced on April 1st), but seems like ASP.NET MVC source code has been released under MS-PL license, a OSI approved open source license.

I’m excited today to announce that we are also releasing the ASP.NET MVC source code under the Microsoft Public License (MS-PL).  MS-PL is an OSI-approved open source license.  The MS-PL contains no platform restrictions and provides broad rights to modify and redistribute the source code.

Codeplex license is not updated yet, but at this point I guess ASP.NET MVC deserves a project of its own as the asp.net codeplex project contains all asp.net pre-release stuff and only one license is allowed per project (thank to Phil for explaining this in the comments) : if this is real effort, they should start managing it as a real opensource project, with public issue tracking, public changeset list, and maybe even contribution from external developers.

The proof that this is not an April’s fool is the AspNetMvc1.Ms-PL.source.zip file that is available for download on Microsoft site: it really contains the MS-PL license. The source under MS-PL is only the system.web.mvc assembly, not the routing that is part of .NET 3.5 SP1 neither the abstractions' one.

I’m really excited to see this happening, seeing a Microsoft product released as OpenSource. Ok, it already happened with the Silverlight Control Toolkit and the Ajax Control Toolkit, but this is a “main stream” library, not just a pack with some controls (please Justin, don’t kill me now).

ASP.NET MVC is a newly released library for building web applications, and lots of contents is available on the web and will be available on book stores. I’m taking part of this evangelization effort both giving talks and writing a book: Beginning ASP.NET MVC 1.0, that I’m writing with Keyvan and that will be published in the June/July timeframe by Wrox (but it’s already available for pre-order on Amazon if you want to make sure they don’t run out of copies)

To honor this announcements, tomorrow evening, after my workshop about ASP.NET MVC, we will go and party with some glasses of good wine. Cheers!!!

Technorati Tags: ,,

CodeClimber Q1 report

If you remember, at the beginning of this year I wrote the usual “New Year’s Resolutions” post: Q1 just finished, so I thought it would have been nice to write a little update on how my resolutions are going.

  • Personal Resolutions
    • Go Back Climbing – This went even worse than the previous year: my wife broke a rib and despite the nice and cold winter no iceclimbing this winter. But we did a lot of Nordic Skiing. Let’s see if we can start going climbing in spring
    • Take part in one triathlon competition – The competition I’m targeting is in July, and till now I started training (running once/twice a week, swimming at least once a week, and going cycling or XC Skiing in the weekend)
  • Blogging and community involvement Resolutions
    • Blog more tutorials and technical articles – The year started with my first series of articles, about how to use Ninject with ASP.NET MVC. Not as much as I would have liked, but more is coming in the future. So, stay tuned.
    • Opensource development – The Subtext project, after ASP.NET MVC release, started with a new home, and some new development. Furthermore I contributed a bit to Ninject. And given what happened last year, it’s an advancement. Q2 will hopefully will even better from the opensource standpoint, as I’ll be actively developing for Subtext
    • Produce some content about ASP.NET MVC in Italian – I recorded a interview about the basics of ASP.NET MVC that has been published on Channel9. And there is something more coming planned together with Microsoft Italy. So, again, stay tuned. And in two days I’ll be giving a talk about ASP.NET MVC for an Italian User Group
    • Redesign my blog – The redesign already happened, Daniela helped me (actually, she did it) while she was recovering from the broken rib. But the design is still a photoshop file. We didn’t found the time to convert it to HTML yet. Furthermore I have to migrate the blog to a new hosting provider before the end of the month, so not sure when I’ll be able to change my skin.
  • Technology Resolutions
    • Enhance my .NET skills – I’m playing around a bit with jQuery and I’m digging into Ninject, so I can consider this resolution as being on the right track. And I even started working a bit with WCF, and that’s another .NET skill I didn’t have and that was nice to get started with.
    • Start developing for Mac/iPhone – I developed an application for the iPhone as part of my job. It was a nice experience even if Objective-C is a bit weird at first.
  • Unplanned
    • User Group meetings– I was the liaison officer between the organization of All4Web day, a multi-community event about RIA, and ugialt.net. And I’m also organizing the next Italian ALT.NET meeting in June.
    • ASP.NET MVC book – The release of the book, due to the delay of the RTM and due to some editorial changes, has been delayed a bit, and I’m still working for applying the latest changes to it.

All in all, some resolution started, others didn’t start, and one even completed already. So not a bad start of the year.

Let’s see what is going to happen in Q2.

Technorati Tags: ,,