Archive for the ‘Web’ Category

MvcConf 2– February 8th, 2011

We’re getting ready for the next version of MvcConf on Tuesday, 2/8/2011 from 8AM-5PM CST! What is MvcConf? MvcConf is a virtual conference focused on one thing: writing awesome applications on top of the ASP.Net MVC framework. Your brain will expl…

Fall 2010 DevConnections Wrap Up

Last week, I had the pleasure of presenting at DevConnections at the Mandalay Bay in Las Vegas, NV. I had a total blast interacting with attendees, fellow speakers and checking out the vendor hall. The logistics for the conference were remarkable given…

Extending MVC Views with DynamicObject

The other day I was working on some features for MVC Turbine when I got a random idea about how we can use a new feature that comes with the Razor view engine (VE). This blog post hopefully will help out some of you in your development or least get you…

Dependency Injection for Filters in MVC3

One of the new features of the Dependency Inject (DI) components from MVC3 is something called a IFilterProvider.  The purpose of this component is to provide a simpler way for MVC applications to interact with filters (action, exception, result, etc….

POCO Results for MVC Actions

Lately, I’ve been working a lot with applications that expose JSON-based services to clients that care to consume their data. All of these services are nothing more than plain Controllers that return a ViewModel that’s rendered as JSON. You might be saying to yourself, “Big deal! All you’re doing is returning a JsonResult to the client! Tell us something new…” Well, as a matter of fact, that’s the whole purpose of this post. ;)

How Do Things Currently Work?

Right now within MVC, you have a explicit convention that a controller must follow for any action it exposes; they must return a type of ActionResult for the runtime to process it correctly.  However, if you have an action that returns a simple value type, ie. integers, bool, Guid, etc. the value assigned to the type is returned. In other words, if you have this controller:

The following is returned by the runtime:

contentresult_guid

Since the value is not an ActionResult, the runtime takes the value and converts its string representation. In this case, the Guid’s value is rendered out as a string on the browser. But what happens when we try to return a complex type, such as:

As you can see, it’s not quite what we expected:

contentresult_complex

What we want instead is to provide the value (and structure) of the complex type back to the caller as JSON…so how do we do it?

Extending the MVC Runtime

In the past I’ve blogged about inferred actions, where I discussed the usage of an ActionInvoker to handle the *dirty* work needed for this feature to work. To accomplish what we need in this case, again we call upon the power of the ActionInvoker (ControllerActionInvoker to be exact) along with an ActionResult, so it can hold the value (result) from our action.

The ControllerActionInvoker class has a method called CreateActionResult which is called after the action method is executed. It is within this method that ContentResult is created for the cases we stated earlier. So, let’s provide our own implementation, PocoInvoker, that does some of the masquerading of our complex type:

As you can see the logic is pretty simple:

  • If the actionResultValue is not an ActionResult…
    • Set it as the ViewData.Model value – in case we want to use it from within the View’s context
    • Create a new PocoResult to wrap the value and comply with the MVC runtime
  • If the actionResultValue is an ActionResult
    • Continue as normal!

From here, most of the work is done by the PocoResult class:

In this sample, the PocoResult class uses Newtonsoft’s JSON.NET as the JSON serializer to render out the complex value out to the caller.

As the comment in the source states, you can use the built JavaScriptSerializer or even inherit from JsonResult and omit all the extra work. I chose JSON.NET since that’s the JSON serializer I used across my projects.

Trying Out the Code

I created an application that interacts with simple person data:

poco_resuls_home

This application provides simple CRUD operations for creating a Person type.  If you look at the code for the Person and PersonController you will run into this little nugget:

The GetList action returns an IList<Person> which contains the values as specified above.  However, when this action method is called the list is returned as JSON:

poco_results_jsonlist

One very important thing to keep in mind is the concept of JSON Hijacking.  Phil Haack has a great post describing how this type of attack works and how ASP.NET MVC prevents these types of attacks from happening.  However, as Matt Hinze blogs, at times we might need to override this behavior for GET requests if we’re creating REST-like services (the purpose of this blog post). So we can implement a simple work around for types that are IEnumerable that wraps the result within a Data element in order to provide safe JSON:

safe_json

In the end, it’s up to you the developer to decide your comfort with these techniques and how best to apply them to your everyday work. I hope this post has provided some knowledge on how you can leverage the ASP.NET MVC runtime to it’s fullest.

Feel free to checkout the code out on github and ask any questions via comments.

Happy Coding!

MVC Turbine and MVC3

I’ve been getting different questions via emails, DMs, IMs, etc. that can be summed up by this question:

Once MVC3 comes out, will I need MVC Turbine anymore to provide Dependency Injection (DI) support to ASP.NET MVC?

There is really no clear answer for this, so all I can say is, it depends :)

For those of you that are not aware, MVC3 has added better support for using Dependency Injection (DI) within different parts of your application. This newly added support applies to:

  • Controllers
  • Filters
  • View Engines
  • etc.

These are the same features that MVC Turbine (Turbine) has offered since we first released V1 almost a year ago. However, in order to provide these and other features, the Turbine codebase has had to handle the plumbing necessary to wire up components in a way to provide first-class DI support. This means that a good chunk of the codebase is just there to ‘hook things up’ within the framework pipeline.  After all, we can’t change the underlying framework so we have to make due with what’s available through the public API.

Since the new extension points that MVC3 exposes provide deeper integration to the framework (pipeline), we can now safely delete all the code that we’ve previously had to write; this is a very good thing. As the old saying goes, we can now stand on the shoulder of giants and focus on providing additional support for MVC applications. :)

The biggest value of add that Turbine gives applications is the “Blade” concept, which is essentially a way to provide an extensibility story to MVC applications. In essence you can build Blades that house cross-cutting support to your applications (i.e. Logging, Persistence Management, ESB Support, etc.) without re-inventing the wheel every time. You write once and use everywhere.

Now that the codebase has shrunk, the team can now focus on providing additional features around Blades as well as (to name a few):

  • Registry Mechanisms ala FubuMVC
    • For example provide registries for filters, model binders, types, etc. in order to lower friction with auto-registration within Turbine.
  • MEF Support
    • Split the work (concerns) of the current underlying container and allow MEF to do the heavy lifting for Turbine-specific components.
  • Reusable Recipes
    • Start a Blade Catalog in which you can now assemble different blades (NHibernate, NServiceBus, log4net, etc.) in order to build applications quicker and repeatable.
  • Better Diagnostics ala FubuMVC
    • Leverage the new hooks and registry concepts to gather and report information about the registered types (controllers, view engines, routes, etc.) to the end user (developer) – to help with trouble shooting scenarios.

Also, with the release of MVC3 it is only natural to increase the version number of Turbine to v3; after all Turbine could not exist without ASP.NET MVC.

I am very excited about the new features and opportunities that MVC3 will bring to ASP.NET stack. To me these features are beyond additions to the framework pipeline but more of an on ramp for creating applications quicker and better on top a great web stack.

Happy Coding!

MvcConf 2010

Recently my good friend and fellow C4MVC junkie, Eric Hexter blogged about an event the ASP.NET MVC community is putting together called, MvcConf.

What is MvcConf?

MvcConf is a online conference where you can learn about real experiences creating MVC applications as well about what the future holds for creating asp.net apps based on MVC.  We have scheduled community members to present on intro and advanced topics using MVC2 and we have some Microsoft product members who will talk about some of the new stuff coming out soon.

Why should I care?

If you’re interested in learning more about development with ASP.NET MVC, why not attend a free event (or session) that will aide that cause? Not only do we have community leaders on MVC but also members of the ASP.NET team, including the one and only PM for the product, Mr. Phil Haack!

You really have nothing to lose with this conference, well, except for some bandwidth since this conference is virtual and broadcast through Live Meeting. :P

Specific Details

So come on, check us out. Here’s the information that you’ll need:

When: Thursday, July 22 8AM – 5PM CDT

Cost: FREE

Where: Virtual (Live Meeting)

Register here: http://mvcconf.com/attend

We’re still working through the final sessions, so the schedule will be posted in a few days. Please bare with us as we coordinate these logistics :)

I’ll see you at MvcConf 2010!

Happy Coding!

MVC Turbine Resources

Recently MVC Turbine has had a lot attention, so I wanted to take the time to say “Thank You!” to those of you that have help promote it, use it, provided feed or giving it a look.

Artwork

In particular I wanted to say a HUGE THANKS to Hugo Bonacci (@hugoware) for donating his artistic talent and creating these awesome logos for the project. Thanks for putting up with my many draft changes and requests. The logos are awesome and I thank you for providing such a great asset to the project!

 

full-logo-large

(horizontal banner)

avatar-large(avatar/icon)

Development Team

Also, I wanted to list out a set of links to blog posts by my self and fellow MVC Turbine member, Darren Cauthon. Darren has provided a lot of great feedback, code and samples which makes the project a lot better.  Thank you Darren for your efforts!

Here are the links from Darren that showcase the extensibility that MVC Turbine provides to applications:

Also, here’s a list of some of the other extension projects that Darren is currently working on:

Podcasts

If you’re an audio learner instead of a visual one, then check out these podcasts in which, yours truly, talks about both ASP.NET MVC and MVC Turbine:

Future Plans

The plan of attack by the dev team is to provide better documentation as well as blog more about examples on ways to use Turbine to extend and power your applications (similar to what Darren is already doing). We want to make the portal site, http://turbineproject.com more than just a redirection to the CodePlex site.  At the same time, we want to roll in bug fixes, fluent registration features and MEF support into v2.2, so check out the GitHub repository for these changes.  Lastly, you can also download the MVC Turbine Project Templates for Visual Studio 2010 from the Visual Studio Gallery.

In Closing

Again, I want to say thank you for taking the time to check out the project and for all the help all you have provided. If you’re interested in helping out, reach out to me either via this blog or start a comment thread out in the Google Group.

Happy Coding!

MVC Turbine v2.1 RTM

Last week, it was tweeted that MVC Turbine v2.1 had reached RTM.

Capture

Release Notes

The from the main ; the features it provides are (same as plus these):

  • Instance Registration to IServiceLocator
    • You can now add an instance of a type to the underlying container so you can address the single instance context.
  • IServiceLocator is registered into the container
    • This allows for components to take in a dependency on IServiceLocator and have it be injected at construction.
  • Batch registration with underlying IoCs
    • Using the batch registration for each IoC to make type registration more streamlined and performant. (StructureMap: Registries, Ninject: Modules, etc)
  • Added the GetUnderlyingContainer extension method to IServiceLocator to allow access for the underlying IoC implemenation.
    • If explicit access to the underlying IoC is needed, the method will query the corresponding member in the implementation and return to the caller.
  • Added extension methods to the ViewContext, and to access the current IServiceLocator without explicitly casting.
  • Property injection support for filter attributes
  • Global MVC filter support
    • MVC filters (,, etc.) can be registered directly into the IServiceLocator and will be applied across every request.

Visual Studio Integration

The Visual Studio Templates have been upgraded for VS 2010 and MVC2 and released to the

After some user feedback, these changes have been made to the code within the template:

  • Added new Services folder with implementation of IMessageService and MessageService to get the Welcome to ASP.NET MVC! message
  • For each IoC, implemented the injection of the container into the CSL as compared to manually doing it (v2 templates)

Project Discussion

All the source is available out on Github for you to check out or fork! Also, if you have any questions or would like to contribute feedback to the project, check out the MVC Turbine Google Group.

If you have any questions, please leave a comment out on the Google Group!

Happy Coding!

A Simple JSON Model Binder

First of, I would like to give a huge thanks to Phil Haack for his awesome blog post, Sending JSON to an ASP.NET MVC Action Method Argument, which shows how really flexible the ASP.NET MVC can be. Also, I owe him a beer next time I see him for saving my behind and providing an actual solution to my original POSTing JSON Data to MVC Controllers post. 

Namaste, Phil!

Client-side JSON ‘Serialization’

In Phil’s post, he mentions that using a model binder falls short because of the lack of validation support:

There’s one key problem with using a model binder to accept JSON. By writing a custom model binder, you miss out on validation. Using his example, if you type “abc” for the Age field, you will get a serialization failure when attempting to serialize the JSON into the PersonInputModel object because Age is an Int32 and the serialization will fail.

He’s absolutely right and, as he mentions, you should use the JsonValueProviderFactory from the ASP.NET MVC 2 Futures library. Funny enough, as he was finishing up his blog post, I was working a simple JSON model binder to show how this is possible with what comes out of the box with MVC2. The source code for this sample is located here, http://github.com/jglozano/samples/tree/master/JSONModelBinder.

The interesting thing in both solutions, is that you do have to some work on the client side to take your javascript structures and convert them into JSON. Phil shows on his post how you can use a JSON plug-in for jQuery to accomplish this. If you read down in the comments, Dave Ward points out that we should be using Crockford’s json2.js to serialize (or stringify) your structure into valid JSON. Funny enough, while working on my sample I had bumped into this StackOverflow post that explains the reason to use Crockford’s script and quotes John Resig’s recommendation (add here for ease of read):

The second major feature of the language is the addition of native JSON support to the language.

I’ve been championing this move for a long time and I’m glad to see it finally arrive in a specification.

In the meantime PLEASE start migrating your JSON-using applications over to Crockford’s json2.js. It is fully compatible with the ECMAScript 5 specification and gracefully degrades if a native (faster!) implementation exists.

In fact, I just landed a change in jQuery yesterday that utilizes the JSON.parse method if it exists, now that it has been completely specified.

There are two primary methods for handling JSON: JSON.parse (which converts a JSON string into a JavaScript object) and JSON.stringify (which convert a JavaScript object into a serialized string).

Once this piece is applied on the client side, there is still some work to be done server side.  For this piece, let’s assume we do not know about IValueProvider and the JsonValueProviderFactory and let’s explore the creation of a model binder (since I already have the code :P ) and some of the issues of taking this approach instead of using the ‘baked-in’ pieces that Phil described.

JsonModelBinder and JavaScriptSerializer

I took a short look at implementing a JSONModelBinder and this is what I came up with:

The code is pretty simple and to the point, except for the interaction with the JavaScriptSerializer piece, which unfortunately does all the heavy lifting for the system. If you’re using .NET 4, the JavaScriptSerializer class has a Deserialize(String, Type) that returns an object of the specified type. However, in .NET 3.5, this method is not available since it’s marked as internal and the only option you have for deserialization is the DeserializeObject(String) method.

If you were to use this method for the example JSON data (in our case, {“Name”:”John User”, “Age”:”29”}) you will get an object of type IDictionary<string,object> as a result.  If you look at Jonathan Carter’s implementation, he leverages the DictionaryValueProvider within the JsonValueProviderFactory, which works great with the new model binding pieces since this type implements IValueProvider.

So, in order to get this piece to work with the type that’s specified via the ModelMetadata, I had to do some work with reflection and extension methods to expose the correct Deserialize method:

Unfortunately, not straight forward but it at the end accomplishes the sending of JSON data to a controller action:

CaptureWhere do we go from here?

Again, although this is functional, you will not get the desired results or leverage the full power of MVC2 new validation components. If you need to support this scenario, PLEASE USE the approach that Phil’s post outlines, it will save you headaches.

If you’re interested in looking at my code, it can be found here: http://github.com/jglozano/samples/tree/master/JSONModelBinder – also, you want to use this with .NET4, there are instructions within the model binder that tell you what to change in order to get things working correctly.

Happy Coding!