Format Filter for ASP.NET MVC -- getting a little more RESTful.

May 14, 2009 05:43 by Seth Webster

I developing http://nsfw4.me, I wanted a closer-to-automated way to add extensionbased format filtering to the different controller methods. For integration'ssake, I wanted the clients which may adopt using nsfw4.me tohave an easy way to interact and understand what the outcomes of those interactionswere.  In building this site on Microsoft's newly released MVC framework,it was easy to create a RESTful interface, but I didn't see a baked in way toformat output based on requested extension.

The approach I took was create two new route entries in Global.asax.cs:
 

1:  
2: routes.MapRoute("DefaultFormat", "{controller}/{action}.{format}", 
3:                           new { controller = "Home", action = "Index", id = "", format = "html"});    
4:  
5: routes.MapRoute("DefaultFormat","{controller}/{action}/{id}.{format}",
6:                            new { controller = "Home", action = "Index",id = "", format = "html"});
7:  
8:  

Now, I would be able to pick up an extension on the requested path and act accordingly. For example, if someone visits a details link for a given object, and theywant .xml, then I can give them a serialized version of that data to suit theirneeds.  If someone visits with the default .html (or nothing at all) we cangive a standard html rendering.  

Enter the FormatFilterAttribute class.  This class hangs on a Controller methodand works its magic in the OnActionExecuted method.  It is in this method thatwe make the determination on how to handle the request.  

Note: Thisfilter requires James Newton-King'sJSON Library.

1:        public override void OnActionExecuted(ActionExecutedContext filterContext)
2:         {
3:             if (filterContext.RouteData.Values.ContainsKey("format"))
4:             {
5:                 var fmt = GetFormat(filterContext);
6:                 var obj = GetResultObject(filterContext);
7:                 switch (fmt)
8:                 {
9:                     case "xml":
10:                         if (null != obj)
11:                         {
12:                             XmlSerializer xs = new XmlSerializer(obj.GetType());
13:                             using (MemoryStream Ms = new MemoryStream())
14:                             {
15:                                 xs.Serialize(Ms, obj);
16:                                 var ret = System.Text.Encoding.UTF8.GetString(Ms.ToArray());
17:                                 filterContext.Result =new PlainTextActionResult(ret);
18:                             }
19:                         }
20:                         break;
21:                     case "json":
22:                         if (null != obj)
23:                         {
24:                             filterContext.Result =new PlainTextActionResult(
25:                                 JsonConvert.SerializeObject(obj, Formatting.Indented));
26:                         }
27:                         break;
28:                     case "html":
29:                         //DO NOTHING
30:                         break;
31:                     default:
32:                         throw new ArgumentException("Invalid format supplied");
33:                         break;
34:                 }
35:             }
36:             base.OnActionExecuted(filterContext);
37:         }
38:  

What's happening Here?

As the MVC framework processes the request to this method, we will intercept afterthe user code has run.  At this time we determine whether there was requestfor something other than a standard render and act accordingly.  If a ViewDataKeyhas been set for the attribute, we look for this object in the ViewData collection,if no key is specified, we try getting the data from the Model property of the currentViewData.  This data is then serialized back to the requesting client.  Currently,2 formats are supported: xml and json.

Try it here:

HTML: http://nsfw4.me/links/details/yahoo
JSON:  http://nsfw4.me/links/details/yahoo.json
XML:  http://nsfw4.me/links/details/yahoo.xml

It also works with creating data.   If you post the proper values (LinkId,LinkUrl) to http://nsfw4.me/links/create.xml, you will receive the result, goodor bad in xml format.  The same also applies for .json requests.


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Migrated this BlogEngine.net Blog to Windows Server 2008... Not Bad

November 15, 2008 10:19 by seth webster

I just finished migrating my blog here to windows 2008 -- I am testing to make sure that I can indeed post an entry. 

The migration wasn't bad though there were definitely manual configuration tweaks that had to be made.  Interesting that MS released such breaking changes... progress!

I had to manually move the registered httpHandlers and httpModules into the <system.webServer> section and rename the section tags to "handlers" and "modules".  I also had to enable detailed errors to figure out what was going on.  

Enabling Detailed Errors: Click Here
Breaking Changes Reference: Click Here

Thanks to Mike Volodarsky for the great info!


Currently rated 4.3 by 3 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

One person's what is another's how...

November 7, 2008 02:48 by seth webster

Defining desired outcomes can be one of the most difficult exercises (sometimes in futility) that an individual or a group can undertake.  There will undoubtedly be a question similar to, "What are you solving for?"  Then someone who just doesn't get it (not my assessment, mind you), responds with a how. In traditional situations, someone reminds the solver, "that's a hhhowwww... What are you solving for?"

I often will take this opportunity when participating or leading these exercises to remind people that Whats and Hows are hierarchical... Every what is another what's how.  For example, if I define an outcome of, "Deliver a 20% increase in wheelbarrow sales for Q4," I have defined a how for the outcome above, "Increase Lawn and Garden sales."  And this what drives to the outcome of, "Enter the lawn and garden market," defined in the previous year.

It is often the case that people in the room are driving the discussion too deep into solving, however, the reason I feel that this discussion is important is to the end that what may be insightful, informative or otherwise beneficial discussions are often cut short and curtailed to avoid defining hows.  Is it possible that having this brief discussion, if targeted, can provide planners (the what people) with invaluable information for making better decisions around the What

Don't get me wrong, however.  Solving too early in the (outcome) planning process can be extremely detrimental to success.  You cannot solve as a unit without cohesively knowing what you are solving for (the what). 

Something else to be aware of is that when people spend an excessive amount of time pushing forward with more hows; trying to solve what in the what planning meeting, it may symptomatic of the fact that there isn't shared vision around that outcome.  Many times, this solve mode is enacted upon an internal (even unidentified) gap realization.  That outcome may be missing the point for the solver.  This can often be solved by getting shared vision, adjusting the outcome phraseology or even adding an additional separate outcome.

Food for thought.


Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Jammin' with the Bad News Blues Band

August 7, 2008 19:31 by seth webster

I've been meaning to post this for a few months now -- I got a call from Johnny Guitar in May to plat this New Orleans benefit at Club Congress.  We had a great time and so did the crowd -- here are some pictures...

DSC_3959 DSC_3970 DSC_3961DSC_3969


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Green, Clean Energy – Plants show us how

August 6, 2008 11:16 by Seth Webster

Scientists at MIT, specifically Dr. Daniel G. Nocera, have announced a major breakthrough, not in energy production per se, but in energy storage. They describe the process as having "captured the essence" of plants' energy storage system. This advancement may very well prove to be the bridge between current solar technology and a technology that will in fact be affordable and scalable enough to make a real difference. Today's solar systems are just not quite "consumable" enough to provide energy for everyone; primarily because they only work when the sun shines and the battery systems leave much to be desired.

The basic idea is that sunlight would still excite photovoltaic cells and produce energy. This energy would be used to power the home (or other building) but instead of losing excess energy, or storing it in complicated, inefficient battery storage systems, the energy would be used to separate oxygen and hydrogen atoms from water molecules. The oxygen and hydrogen are later combined in a fuel cell and viola!

Read more here: http://web.mit.edu/newsoffice/2008/oxygen-0731.html


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Enough with the lightning!

August 5, 2008 15:24 by Seth Webster

AzMonsoon-
Originally uploaded by swebsterinaz
The Santa Catalina mountains in the background give a wonderful backdrop to the ferocious lightning!

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

More Great Lightning...

August 5, 2008 15:23 by Seth Webster

AzMonsoon--2
Originally uploaded by swebsterinaz
You can see the taillights of a car that passed during this 8 second exposure...

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

A great monsoon show tonight

August 5, 2008 15:22 by Seth Webster

AzMonsoon--3
Originally uploaded by swebsterinaz
Mother nature gave us a great show tonight! We had some of the best lightning I've seen this season! I was only able to get about 5 shots off before it started to dump buckets of water on me (and my camera) but here's a small sampling...

Currently rated 4.7 by 3 people

  • Currently 4.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Reading images from the disk in Silverlight 2.0

August 5, 2008 08:59 by seth webster

Jeff Prosise's Blog Post, and the comments explain how to read an image (after it is selected by the user) from the disk.  This post proved to be incredibly useful in the application we are currently developing for desktop publishing.  Thanks Jeff & Friends!


Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Blog Migration - Success!

August 4, 2008 12:55 by seth webster

For the subscribers, I apologize if you have a slew of new and re-used posts in your reader.  I have been in the process of migrating from Community Server to SubText and then to BlogEngine.NET.  It seems as though BlogEngine.NET has a more active community than SubText which is run by the very busy Phil Haack of Microsoft fame.  I am happy to report that the migration is, for now, complete.

I decided to write a migration tool that would move the data over - I did so using the BlogML, MetaWeblog & Blogger apis, C#, WPF, and the Cook Computing XmlRpc library.  There are tools (one even comes with BlogEngine.NET) but they don't move over the linked images and since some of the posts that survived my last migration have pictures, I didn't want to move them manually... 

There was some effort involved and the code needs refactoring but all in all the utility works well.  Once I have the time to clean it up and if anyone is interested, I will post the utility and code here.


Currently rated 4.3 by 3 people

  • Currently 4.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5