Showing posts with label MvcContrib. Show all posts
Showing posts with label MvcContrib. Show all posts

5/26/2008

LocalizationFilterAttribute

The MVC Framework is highly extensible, which makes it really fun to tinker around with ;) . I just got done integrating jQuery based AJAX and JSON request/response patterns, using different variations of the work laid out by Aaron Lerch in Unifying Web "Sites" and Web Services with the ASP.NET MVC Framework and Nikhil Kothari in Ajax with the ASP.NET MVC Framework . I was surprised to find so many different extension points built into the framework, it really gives you the power to do just about anything.

I though it might be great to leverage this extensibility and add localization into my new WebSite/WebService monster.

When it comes to localization on the human web, we have a few choices.

  1. The Accept-Language HTTP Header Field is supported by most browsers and a lot of sites.
  2. Some sites, like MSDN Library, allow users to put the desired language-culture specifier in the request URL. (en-US, es-ES, fr-FR, etc).
When I was working for Microsoft in Japan, I loved the fact that KB articles and the MSDN library supported language-culture specifier in the request URL. This allowed me to do my research in English, change the URL from 'en-US/whatever' to 'ja-JP/whatever', and send the resulting URL to my native Japanese customers. So option #2 is what I chose.

I'm using the SimplyRestfulRouteHandler to establish my routing, so this is what my route registration looked like:

SimplyRestfulRouteHandler.BuildRoutes(RouteTable.Routes, "{lang}");

You could also do it the old-fashioned way:

RouteTable.Routes.Add(new Route(
"{lang}/{controller}",
new {Action = "Index", Controller = controllerName},
new RouteValueDictionary(new { httpMethod = "GET" }),
new MvcRouteHandler()));

Now the Controller.RouteData.Values["lang"] key will store the specified language-culture for a GET request like 'http://msdn.microsoft.com/en-us/library', where library is the controller.

Next, I want to snag that value and use it to set my thread's CurrentCulture/CurrentUICulture properties. I also want to make sure that I revert the thread's settings when my action is done processing because these properties won't be reverted if our thread is executing in a ThreadPool.

Fortunately, the ActionFilterAttribute class exposes an OnActionExecuting() method which is triggered before an action executes, and a OnActionExecuted() method which is triggered right after. So, I created the following LocalizationFilterAttribute class to do the dirty work for me.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
public class LocalizationFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Controller c = filterContext.Controller as Controller;
if(c == null)
return;

string lang = c.RouteData.Values["lang"] as string;
if(lang == null)
return;

try
{
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
}
catch
{
throw new NotFoundException("The specified language " + lang +
" was not found.");
}
}

public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InstalledUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture;
}
}

It's a good idea to reset the culture information in the Application_Error (Global.asax.cs) method as well, in case an unexpected exception causes the action to terminate.

protected void Application_Error(object sender, EventArgs e)
{
Thread.CurrentThread.CurrentCulture = CultureInfo.InstalledUICulture;
Thread.CurrentThread.CurrentUICulture = CultureInfo.InstalledUICulture;
}

That's all there is to it. You can throw this filter attribute on any controller class you want, and you're ready to localize.

4/27/2008

SimplyRestfulRouteHandler Sample

MvcContrib is packed with quite a few gems. One of these is the SimplyRestfulRouteHandler, a route utility created by Adam Tybor.

Using the SimplyRestfulRouteHandler, the following 10 Routes are assigned to the 8 Actions below.
(Blatantly lifted from Adam's site)

ActionUrlHttp MethodForm Method
Show[controller]/[id]GET
Create[controller]POST
Update[controller]/[id]PUT
Update[controller]/[id]POSTPUT
Destroy[controller]/[id]DELETE
Destroy[controller]/[id]POSTDELETE
Index[controller]GET
New[controller]/newGET
Edit[controller]/[id]/editGET
Delete[controller]/[id]/deleteGET

The route handler is surprisingly easy to use, but it can be tricky to set up if you are not familiar with the new method signatures of the latest MVC source code refresh.

I created a sample app based on the MVC HomeController that highlights the 8 actions defined by the SimplyRestfulRouteHandler. To follow along, you will need the 4/16 MVC source code refresh (build 0416) and the 4/19 release of the MvcContrib library (0.0.1.101).

First you should create a new 'ASP.NET MVC Web Application' project from the 'My Templates' portion of the 'New Project' dialog. If you use the template of the same name under the 'Visual Studio installed templates' portion, you will be using the latest official release of MVC and not the source code refresh.

In the global.asax.cs file, replace the RegisterRoutes method with the following.

public static void RegisterRoutes(RouteCollection routes)
{
SimplyRestfulRouteHandler.BuildRoutes(routes);
}

This will allow the route handler to build all 10 routes for you, based on templates listed in the table above.
Next we open the HomeController.cs file and add the corresponding actions.


public ActionResult Show(string id)
{
ViewData["Title"] = "Show";
ViewData["Message"] = "This will <em>Show</em> resource " + id;

return RenderView("Index");
}

public ActionResult Create()
{
ViewData["Title"] = "Create";
ViewData["Message"] = "This will <em>Create</em> a new resource";

return RenderView("Index");
}

public ActionResult Update(string id)
{
ViewData["Title"] = "Update";
ViewData["Message"] = "This will <em>Update</em> resource " + id;

return RenderView("Index");
}

public ActionResult Destroy(string id)
{
ViewData["Title"] = "Destroy";
ViewData["Message"] = "This will <em>Destroy</em> resource " + id;

return RenderView("Index");
}

public ActionResult Index()
{
ViewData["Title"] = "Index";
ViewData["Message"] = "This is the <em>Index</em>";

return RenderView("Index");
}

public ActionResult New()
{
ViewData["Title"] = "New";
ViewData["Message"] = "This will create a <em>New</em> resource";

return RenderView("Index");
}

public ActionResult Edit(string id)
{
ViewData["Title"] = "Edit";
ViewData["Message"] = "This will <em>Edit</em> resource " + id;

return RenderView("Index");
}

public ActionResult Delete(string id)
{
ViewData["Title"] = "Delete";
ViewData["Message"] = "This will <em>Delete</em> resource " + id;

return RenderView("Index");
}

For this sample app, all we really want to do is simply display a brief message letting us know which action the user wanted to take. The generated 'Index.aspx' view is fine for this, so we can set the viewName parameter of the RenderView() method to "Index" for all actions, as shown above.

Now we have just about everything we need. Let's move on to the 'Site.Master' file and enable the user to generate all 8 actions via click events.

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

<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
<%= ViewData["Message"] %>
<p>
To learn more about ASP.NET MVC visit
<a href="http://asp.net/mvc" title="ASP.NET MVC Website">
http://asp.net/mvc</a>.
</p>
</asp:Content>

Now we have just about everything we need. Let's move on to the 'Site.Master' file and enable to user to generate all 8 actions via click events.

<ul id="menu">
<li> <%= Html.ActionLink("Show GET", "Show", "Home", new { @id="1" }) %> </li>
<li> <%= Html.ActionLink("Index GET", "Index", "Home")%> </li>
<li> <%= Html.ActionLink("New GET", "New", "Home")%> </li>
<li> <%= Html.ActionLink("Edit GET", "Edit", "Home", new { @id = "1" })%> </li>
<li> <%= Html.ActionLink("Delete GET", "Delete", "Home", new { @id = "1" })%> </li>
<li>
<form action="<%= Url.Action("Create", "Home") %>" method="post" >
<a onclick="parentNode.submit();">Create POST</a>
</form>
</li>
<li>
<form action="<%= Url.Action( "Update", "Home", new { @id = "1" }) %>" method="post" >
<input type="hidden" name="_method" value="put" />
<a onclick="parentNode.submit();">Update POST</a>
</form>
</li>
<li>
<form action="<%= Url.Action( "Destroy", "Home", new { @id = "1" }) %>" method="post" >
<input type="hidden" name="_method" value="delete" />
<a onclick="parentNode.submit();">Destroy POST</a>
</form>
</li>
</ul>

If you were watching closely, you should have noticed that the POST events have a hidden input element named "_method" who's value is an HTTP method (PUT or DELETE). Well, most browsers don't support these two methods so we sometimes need a clever way of initiating these requests. Adam was kind enough to wire up our Destroy and Update Actions so that they fire when the route manager receives standard HTTP PUT and DELETE methods OR when it receives a browser-friendly HTTP POST request with a PUT or DELETE "_method" defined.

Next we need to make the form elements of our menu look pretty, so we add the following to our 'Site.css' file.

ul#menu li form
{
display: inline;
list-style: none;
}

And that's all there is to it. You should be able to launch the application and click on all of the menu items to generate any of the 8 RESTful actions.

You can download the complete source for this sample project here.