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 explode from taking in so much hard core technical sessions. Sounds fun eh?  This is a community event and we want the best and brightest sharing what they know.

We intend to record each session and make them available online for viewing. We intend to make the videos available free of charge, depending on conference sponsorships.

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 Scott Guthrie, Scott Hanselman, Phil Haack and Jon Galloway!

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

Conference Details

When: Tuesday, February 8th, 2011 8AM – 5PM CST

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 2!

author: Javier G. Lozano | posted @ Thursday, January 20, 2011 12:38 AM | Feedback (2)

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 there was approximately 2,800 people in attendance!

For those of you that attended my presentations, thank you! I hope you were able to get something out of them; I had a blast presenting and interacting with you in each of them.  Also, I had a great time with the open spaces sessions. There was lots of good interaction from the people in the ones I participated in.

As a recap, I’ve mentioned that my presentation material is out on Github, so you can download both slides and demos very easily. If you didn’t get a chance to write the location, please use the links below:

Again, thanks for checking out my session and I hope that you too had much of a blast as I did! If you have any questions or comments, please feel free to ping me.

Happy Coding!

author: Javier G. Lozano | posted @ Saturday, November 06, 2010 4:03 PM | Feedback (6)

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 your creative juices going.

@View with Razor Views

One of the new features that ships with the Razor VE is the ability to set ViewDataDictionary values through the use of a DynamicObject property. The following code shows how to do this:

The ViewModel.Message call is the equivalent of ViewData[“Message”], all which is done via the magic of DynamicObject. Internally, the controller uses an instance of the internal type DynamicViewDataDictionary in order to handle the get/set for values.  This same instance is used to set the value of the View property for the WebViewPage type, the base type for all Razor-based views.  Taking this simple approach we will implement something that will allows our views to tap into common services without dealing with the specifics of service resolution.

@Service Extension Point

Let’s first start by looking at the DynamicObject property that will wire things up for us.  What we need here is a way to link a property name to an object instance that will satisfy the method call:

We need to translate the @Service.MessageService.GetWelcomeMessage() piece into a method call. We do this by taking the convention of @Service.ServiceContract.Method() and providing a way to enforce it. We do this via the DynamicLocator class:

As you can see, the DynamicLocator is a type that inherits DynamicObject and uses StructureMap to do the heavy lifting of service resolution.  Since we’re treating every property as the service contract, we need to override the TryGetMember method to get the instance of the type that implements said contract. If the name doesn’t match a registered type, we need to throw an exception to inform the invalid service type. From here what we need to do is wire this type into the view, more specifically we need to wire this to the Service property of the view. We can do this by providing our own base view class:

This DynamicPage type exposes a Service which, as you can see, is a dynamic object; a DynamicLocator type to be more specific.  Now, we all need to do is tell the Razor view engine to use this as the base type for the views it generates.  We do this by modifying the Web.config within the Views folder:

Now we run things and see the following output:

Capture

Wrap Up

I hope this blog post can help some of you out, or at least get your creative juices flowing. As you can see, it’s pretty simple to build your own conventions and flow once you get to grok the pieces that make up the framework.  As always, check out the source and feel free to leave any comments!

Happy Coding!

author: Javier G. Lozano | posted @ Thursday, October 21, 2010 12:45 AM | Feedback (9)

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.). In the previous versions, trying to achieve something like providing DI support to filters was doable, it just required deeper integration into the MVC runtime.  The IFilterProvider interface is defined as:

As you can see, it’s a pretty simple interface that can enable lots of opportunities if used in the right context.  The MVC bits ship with an implementation named FilterAttributeFilterProvider that parses the attributes defined on actions and controllers and returns an aggregated list for the runtime to process. So, how can we leverage this class to provide DI to these attributes? Let’s take a look :)

Injecting Dependencies into Attributes

For this sample, I will use Ninject as the DI container to inject, via properties, dependencies into the attributes. The dependency is a simple IMessageService:

And it’s consumed by the MessageAttribute class:

The MessageAttribute class is using Ninject’s Inject attribute to inform the container that IMessageService needs to be injected as a property; in other words, inject after the creation of the attribute.  From this point, all we need to allow for the injection to happen – this is where FilterAttributeFilterProvider comes into play with a few minor tweaks:

By overriding the GetFilters method and using the IKernel instance that has the IMessageService (or any other) registration, all of the work can be contained within the InjectableFilterProvider class. This allows us to easily re-use this provider within any MVC3 application (that uses Ninject of course!) and provide DI support to any attributes for any controller.  From here, all we need to do is register the filter and pass it the correct container instance:

As you can see these new DI features within MVC3 make things that used to be hard (or awkward) pretty straightforward with minimal work. Feel free to check out the full sample out on Github and leave any questions as comments!

Happy Coding!

author: Javier G. Lozano | posted @ Tuesday, October 12, 2010 11:37 PM | Feedback (15)

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!

author: Javier G. Lozano | posted @ Wednesday, October 06, 2010 11:51 PM | Feedback (8)