Lock user interface plugin – uiLock
I was asked to create a user interface locker using jQuery. The main idea behind was to lock all user interactions with the website while jQuery AJAX loads block contents and unlock when content is loaded. So I thought I would share the code and released it as a jQuery plugin called uiLock. The plugin extends jQuery and adds two main functions called $.uiLock(); and $.uiUnlock(); Here is how toUsing of JSON Result in Asp.net MVC 1.0
In a post few month back , i showed how can i simulate a callback using JQuery and ASP.NET with my experimental FlickrXplorer project. More detail on this can be found at the following URL
Now, what i have done here is basically, i did an AJAX call to the controller and rendered the view result in a div. One thing about this way is that i am able to make the view strongly typed as i first rendered view using standard way with all the strongly type ViewData.Model. It is nice for rendering views with small amount of html in it (Like , tag lists), but slow for big outputs. The best practice for all these is to use the JSONResult. Here, i will show a small example of how i render the comment list in FlickrXplorer using JSON result and JQuery $.get in conjunction to make the AJAX request.
First, let’s see how the controller looks like. Assume that there is a controller named CommentController and we have an action named List
[AcceptVerbs(HttpVerbs.Get)] public ActionResult List(string photoId, int ? index, int? page) { int skip = index == null ? 0 : index.Value*page.Value; int take = page == null ? int.MaxValue : page.Value; PhotoCommentViewData comments = new PhotoCommentViewData(); try { comments = model.GetComments(photoId, skip, take, false); return Json(comments); } catch (Exception ex) { /// do some exception tracking } }
As it seems, it gets the list of comment from its underlying model and then pass it through JSON result. Optionally, i limited that the action should only be accepting GET calls as it is a list request.
Now, coming back to JavaScript we first need to do a GET request to this action and syntax for doing it in JQuery style:
$.get(url, { index: index, page: page }, function(result) {
processComments(url, result, index, page, loaderTarget, contentTarget); [strike though is not covered in the post]
}, "json");
The first argument is the comment list URL, this is constructed in server side using Url.Action and then passed in the JS that also ensures the routing setup, second is the JSON string for params, third is the callback for the result it fetches and final is the type of response it should contain.
Inside processComments , i basically do some DOM operations to build the necessary html block
$("#layout") .append($("<tr/>") .css({'vertical-align' : 'top'}) .append($("<td/>") .attr("class", "said") .append($("<strong/>") .append($("<a/>") .attr("href", "/Photo/NsId/" + comment.Author) .css({ 'color': '#0063DC', 'text-decoration': 'none'}) .append(comment.AuthorName)) .append(" says: ")) .append($("<br/>")) .append(comment.Text)));
So, there is a “layout” panel in the comment container where i am to add the dynamic html. jQuery has this nice way of adding html in a chain and elements under it. For example i want to render a html link with some custom CSS and i want to point that to some URL as well.
Using jQuery , i would do
$("<a/>") .attr("href", "/Photo/NsId/" + comment.Author) .css({ 'color': '#0063DC', 'text-decoration': 'none' }) .append(comment.AuthorName)
This will render a html tag something like
<a href=”/photo/NsId/x@y” style=”color:#0063DC, text-decoration:none”>Mehfuz </a>
The rule is that you start a element with $(…) in XHTML style then add necessary attributes, styles and text and it will automatically give you a well-formed html, moreover you can nest it as you like with other elements.
The above block finally produces a look similar to
There are few other JS that is responsible for generating the pager control which is not covered in this post, for this and more you can take a look at the latest bits of FlickrXplorer under www.codeplex.com/flickrXplorer .That’s so far and if you have some cool ideas to share on this, let me know.
Hope that helps.
6 Tips for ASP.NET MVC Model Binding
Model binding in the ASP.NET MVC framework is simple. Your action methods need data, and the incoming HTTP request carries the data you need. The catch is that the data is embedded into POST-ed form values, and possibly the URL itself. Enter the DefaultModelBinder, which can magically convert form values and route data into objects. Model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment.
Here are some tips on how to take advantage of model binding in your MVC projects.
Tip #1: Prefer Binding Over Request.Form
If you are writing your actions like this ..
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create() { Recipe recipe = new Recipe(); recipe.Name = Request.Form["Name"]; // ... return View(); }
.. then you are doing it all wrong. The model binder can save you from using the Request and HttpContext properties – those properties make the action harder to read and harder to test. One step up would be to use a FormCollection parameter instead:
public ActionResult Create(FormCollection values) { Recipe recipe = new Recipe(); recipe.Name = values["Name"]; // ... return View(); }
With the FormCollection you don’t have to dig into the Request object, and sometimes you need this low level of control. But, if all of your data is in Request.Form, route data, or the URL query string, then you can let model binding work its magic:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Recipe newRecipe) { // ... return View(); }
In this example, the model binder will create your newRecipe object and populate it with data it finds in the request (by matching up data with the recipe’s property names). It’s pure auto-magic. There are many ways to customize the binding process with “white lists”, “black lists”, prefixes, and marker interfaces. For more control over when the binding takes place you can use the UpdateModel and TryUpdateModel methods. Just beware of unintentional binding – see Justin Etheredge’s Think Before You Bind.
Tip #2: Custom model binders
Model binding is also one of the extensibility points in the MVC framework. If you can’t use the default binding behavior you can provide your own model binders, and mix and match binders. To implement a custom model binder you need to implement the IModelBinder interface. There is only method involved - how hard can it be?
public interface IModelBinder { object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext); }
Once you get neck deep into model binding, however, you’ll discover that the simple IModelBinder interface doesn’t fully describe all the implicit contracts and side-effects inside the framework. If you take a step back and look at the bigger picture you’ll see that model binding is but one move in a carefully orchestrated dance between the model binder, the ModelState, and the HtmlHelpers. You can pick up on some of these implicit behaviors by reading the unit tests for the default model binder.
Scott Hanselman demonstrates a non-trivial model binder in his post “Splitting DateTime – Unit Testing ASP.NET MVC Custom Model Binders”. One detail I want to call out about Scott’s DateTime splitter is how you still don’t need to use Request.Form when building the model. Inside the GetA<T> method you’ll see how Scott uses the binding context’s ValueProvider property to fetch data. The ValueProvider represents an amalgamation of all data from the request’s posted form values, routing data, and query string. Scott’s example is great, but it is missing one detail – the propagation of binding errors.
If the default model binder has problems putting data into your object, it will place the error messages and the erroneous data value into ModelState. You can check ModelState.IsValid to see if binding problems are present, and use ModelState.AddModelError to inject your own error messages. See this very simple tutorial for more information on how ModelState and HtmlHelpers can work together to present validation errors to the user.
If you scroll down the comments to Scott’s post you’ll see Sebastien Crocquesel’s patch for Scott’s code. If a conversion fails, Sebastien’s code will use ModelState.AddModelError to propagate the error. Both the controller action and the view can look in ModelState to see if there was a binding problem. The controller would need to check ModelState for errors before saving stuff into the database, while the view can check ModelState for errors to give the user validation feedback. One important note is that the HtmlHelpers you use in a view will require ModelState to hold both a value (via ModelState.SetModelValue) and the error (via AddModelError) or you’ll have runtime errors (null reference exceptions). The following code can demonstrate the problem:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(FormCollection Form) { // this is the wrong approach ... if (Form["Name"].Trim().Length == 0) ModelState.AddModelError("Name", "Name is required"); return View(); }
The above code creates a model error without ever setting a model value. It has other problems, too, but it will create exceptions if you render the following view.
<%= Html.TextBox("Name", Model.Name) %>Even though you’ve specified Model.Name as the value for the textbox, the textbox helper will see the model error and attempt to display the “attempted value” that the user tried to put in the model. If you didn’t set the model value in model state you’ll see a null reference exception.
Tip #3: Custom Model Binding via Inheritance
If you’ve decided to implement a custom model binder, you might be able to cut down on the amount of work required by inheriting from DefaultModelBinder and adding some custom logic. In fact, this should be your default plan until you are certain you can’t subclass the default binder to achieve the functionality you need. For example, suppose you just want to have some control over the creation of your model object. The DefaultModelBinder will create object’s using Activator.CreateInstance and the model’s default constructor. If you don’t have a default constructor for your model, you can subclass the DefaultModelBinder and override the CreateModel method.
Jimmy Bogard has an example of sub classing the DefaultModelBinder in his post titled “A Better Model Binder”.
Tip #4: Using Data Annotations for Validation
Brad Wilson explains everything beautifully in this post: DataAnnotations and ASP.NET MVC.
I encourage you to go read Brad’s post, but if you are in a hurry, here is a summary:
.NET 3.5 SP1 shipped a System.ComponentModel.DataAnnotations assembly that looks to play a central role as we move forward with the .NET framework. By using data annotations and the DataAnnotationsModelBinder, you can take care of most of your server-side validation by simply decorating your model with attributes.
public class Recipe { [Required(ErrorMessage="We need a name for this dish.")] [RegularExpression("^Bacon")] public string Name { get; set; } // ... }
The DataAnnotationsModelBinder is also a great sample to read and understand how to effectively subclass the default model binder.
Tip #5 : Recognize Binding and Validation As Two Phases
Binding is about taking data from the environment and shoving it into the model, while validation is checking the model to make sure it meets our expectations. These are different different operations, but model binding tends to blur the distinction. If you want to perform validation and binding together in a model binder, you can – it’s exactly what the DataAnnotationsModelBinder will do. You can also find samples like Automatic Model Validation with ASP.NET MVC, xVal, Castle, and a Custom Binder (John McDowall), and Enterprise Library Validation Application Block with MVC Binders (Steve Michelotti). However, one thing that is often overlooked is how the DefaultModelBinder itself separates the binding and validation phases. If all you need is simple property validation, then all you need to do is override the OnPropertyValidating method of the DefaultModelBinder.
Tip #6: Binders Are About The Environment
Earlier I said that “model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment”. Generally, when we think of binder we think of moving data from the routing data and posted form values into the model. However, there is no restriction of where you find data for your model. The context of a web request is rich with information about the client. A good example is another Scott Hanselman post on automatically binding the user’s identity into a model see: IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing.
In Conclusion
Model binding is beautiful magic, so take advantage of the built-in magic when you can. I think the topic of model binding could use it’s own dedicated web site. It would be a very boring web site with lots of boring code, but model binding has many subtleties. For instance, we never even got to the topic of culture in this post.
Do you have any model binding tips?
Twitter JSON/JSONP API URL
It is Friday and we don’t want to read long posts and tutorials. So today’s post is going to be short and sweet. I’ve been playing a lot with Twitter lately. I wrote some jQuery and javascript functions that get user details, etc. I will share it with you next week. But for today, I would like to share Twitter’s JSON and JSONP API URL. I am sharing it because it was hard to find it first. ILife and Times of an ASP.NET MVC Controller
The May issue of MSDN Magazine is now on-line with my article “The Life and Times of an ASP.NET MVC Controller”.
In this article, I will dissect the ASP.NET MVC framework and look at how controllers work. I'll explain how the framework interacts with your controllers and how you can influence those interactions. I'll look at controller factories, controller actions, action filters, and action results as well.
I don’t like programming by coincidence, and I hope this article gives you everything you need to work confidently with MVC controllers. In addition to the technical details, I also believe you have to properly apply a technology to make great software – thus the next installment of Extreme ASP.NET in July will cover some guiding principles to keep in mind when developing applications with the ASP.NET MVC framework.
Looking even further down the road (September seems so far away), I’m not sure what I’ll dig into next. Will it be web forms? More ASP.NET MVC? If there is something you want to hear about that is related to the ASP.NET server-side runtime - drop me a line or leave a comment.
Twitter Marketing: Why You Don’t Need to Mass Follow Users
A few days ago Twitter announced on their status blog that all Twitter users are only allowed to follow a maximum of 1000 people a day. This rule was designed to cut down on ‘follow spam’, the act of following many Twitter users in order to get them to follow you back or click on your links.
When combined with the already existing limit based on follow ratios, this means that it will be more difficult for marketers or self-promoters to rapidly increase their Twitter follower count by following many people. The old days of following thousands of users a day to get thousands of followers back are gone.
That’s not to say the strategy of mass following users to increase your Twitter followers doesn’t work anymore. It does. Why? Because many people use tools to auto-follow anyone who follows them. And there are new users who think its only polite to reciprocate. So you can easily get tens of thousands of followers from this strategy over time.
I see quite a few people still practicing this method. Some are social media enthusiasts or consultants, some are internet marketers or bloggers. All of them are people who want to get something in return. They want to:
- Make money. The goal is to monetize Twitter users by linking and recommending products or services, either their own or others if they are an affiliate. They do this by tweeting out links and sending automated direct messages with the same offers when someone follows them back.
- Improve their reputation. They amass followers with the aim of improving their reputation in a specific field like marketing or social media. They also use their followers to boost their prominence on other social arenas like Digg or Facebook.
- Get more visitor traffic. More followers means more visitors to their websites so they can get more subscribers, readers and members. They also want the ability to make specific content go ‘viral’ and become popular by sharing it with their followers.
Many people think that to achieve all of the above, they need to build a large list of Twitter followers and broadcast links to get free traffic. It’s a simple strategy. The more followers you have, the more people listen to you, and the easier it is to spread your messages.
But do you really need a large number of followers to promote yourself successfully on Twitter? The answer is no. Not at all. But many people still persist in mass following users. Let’s look at some of the reasons why you don’t need to use this marketing tactic.
Low-Value Followers: Automatons, Spammers and Self-Promoters

Image Credit: ittybittiesforyou
Many products on Twitter marketing have been released by internet marketers looking to profit from the growing interest in Twitter. These products give you the same blueprint: just get more twitter followers. All you need to do is to follow many users everyday, drop non-mutuals and then follow more. Repeat until you get a ton of followers and look like a social media rockstar. If people follow you, you must be awesome, right?
The only problem is that these are low-value followers. Not because they are dumb or socially inferior but because a good amount of these followers are not ultra-targeted, active or responsive. Many of them are self-promoters, spammers or automated feed accounts. These people aren’t interested in you. They don’t care about you. They didn’t REALLY opt-in. They even followed you automatically, didn’t they?
If we were to draw comparisons to a email list or newsletter, these types of people are the ones who would use a temporary email address to sign up so they can get your freebie and disappear. Most of them aren’t going to end up retweeting your stuff, most of them don’t even read your tweets. Most of them don’t give a damn about your ideas.
It’s not about the follower count, its about conversions. A carefully cultivated list of 1000 followers can beat a list of 10,000 twitter followers anytime when it comes to spreading content or getting traffic/sales. A social media strategy that only involves mass following all sorts of people and shooting out links in order to hook buyers or readers is quite inadequate.
Low-value followers are incredibly easy to get and the only positive thing about them is that they’ll make you look good. Judging influence by the follower count is something that people do. It’s social proof. So you have 80,000 followers. You can probably start a social media consulting business and tell everyone that you’re an expert. Or write that ebook and flaunt your follower count on the sales page. You can fool a lot of people and you’ll make money too.
So play the Twitter game of mass adding and dropping users for a few months. You may even meet some cool people but don’t assume that you have 50,000 users who actually read your tweets or are interested in you. They aren’t. And you’re irrelevant to them.
Remember, you’re not getting natural opt-in follows preempted by interest. All you have is an inflated number. Maybe you think that’s something to be proud of but if a 7 year old kid can press a auto-follow button and get 500 followers in 24 hrs, you’re not that impressive.
Twitter Marketing is More Than Just Getting Followers

Image Credit: badjonni
Unless you are a celebrity or a famous brand, you will never get hundreds of thousands of natural follows from people who are interested in what you have to say. If you want to look like a VIP, you can fake it by manipulating follower counts like most self-promoters.
But do you really think that’s effective Twitter marketing? Sometimes I feel that marketers should stop this obsession with volume and carefully think about cultivating a better follower list as well as other more effective ways of using Twitter for marketing.
I don’t want to blindly label all mass-following users as spammers. Some are not malicious nor are they aggressive self-promoters. I’m just questioning the overwhelming focus on this tactic, as if its the only way to accumulate influence or market yourself on Twitter. It’s not.
This isn’t an attack on anyone. If you think that mass following many users to boost your follower count is great, keep doing it. I’ve got no problems with that. I’m just offering my opinion on why I think its flawed. This comes from having actually experimented with this strategy, so it’s not just theoretical postulations.
In my opinion, while having a large number of Twitter followers is not a bad thing, there are some other key factors you should consider if you’re want to use Twitter to market yourself or your website/brand. These are points which I think are quite important even if your ONLY reason for using Twitter is to make money or get traffic.
The most important thing you should remember: It’s not about the number of Twitter followers you have, its about who follows you and the responsiveness of your audience.
Who Follows You: The People Who Give You Their Attention

It matters who reads your tweets. Are these people interested in you or your business? An interested follower is naturally more engaged with whatever you put out on Twitter. People who automatically follow you do not count as interested followers.
Are your followers active? Active users share your links, they give you feedback, they talk to you. Automated or semi-automated users are not active users that will interact with you.
And do the people who follow you have influence? Would you rather get 50 retweets from users with 10 to 100 random followers? Or you rather get 10 retweets from influencers in same niche, with all of them having 1000 to 10,000 very relevant followers?
How about tweeting out a link or idea and having someone with a blog in the same niche write about it and link to you? Can your army of auto-followers offer the same? Not every Twitter user has the same audience size. Some users can reach more people much faster and these are the ones that can help you.
This is not to suggest that the average twitterer is useless but to highlight the unequal influence of each user. Who follows you matters a great deal because powerful Twitter marketing involves not just link-blasting but networking and relationship development.
Responsiveness of Your Audience: Are They Engaged?

Image Credit: seizetheday
Responsiveness is the degree to which your Twitter audience is engaged with whatever messages you put out on Twitter. A responsive audience connects with you, retweeting your links and answering your questions. They interact with your Twitter stream.
When we talk about a responsive email list, we’re talking about subscribers who are willing to buy or take action on your offers. Responsive Twitter followers are similar: they take action on your tweets by spreading them or talking back to you.
An easy way to measure responsiveness is to ask a question and see how many people respond. The no. of link clicks and retweets are other factors as well but anyone can click on a random link: it just shows that they’re interested in the link title or story. But are they interested in you? Actual responses to your queries are a good measure of that.
A responsive Twitter audience naturally develops when people are interested in you, what you do and who you are. Celebrities have the most responsive followers, many of their subscribers even sign up for a Twitter account just to interact with their tweets. They’re actively looking forward to reading new tweets from their favorite personality. This anticipation and interest makes them a perfect audience for conversions and call-to-actions.
If you’re not already famous, you will have a tougher time building a responsive audience because you don’t get natural interest in you from the start. One way to generate this interest is to develop a reputation in your field so that your name or brand is known.
This means you shouldn’t just spend your whole day following/unfollowing, tweeting links and chit-chatting. You have to work at your brand away from Twitter. If you put out an interesting tool or piece of content, you’ll get interest. If you’re selling a product that solves a problem, you’ll get interest. As you become more known online, you will get people following you.
When on Twitter itself, you can develop responsiveness through reciprocation. By actively interacting with other users, you will induce them to pay more attention to your updates. But don’t just send out updates and only talk to people who reply to your tweets. Actively monitor and engage users. Over time they will warm up to you and responsiveness will increase.
Remember, you don’t just want a large follower count. You want a responsive group of followers. People who are genuinely interested in you and people who will click on your links, retweet you or respond to your queries. Ultimately this group of Twitter followers can help you popularize your website or grow your business.
My Follow Strategy for Twitter Marketing

Image Credit: fotographix.ca
Instead of autofollowing a ton of people and rinsing them out to get mutual followers who are either not interested or very poorly interested in you, go for ultra-relevant Twitter users.
There are two types of twitter users you can target: people who have the power to help your business grow and the average user who is a potential customer. Whichever type you choose depends on your goals and what you want to get from Twitter.
Generally I’m more in favor in targeting twitter users who can best promote my business interests so you can get customers/buyers/readers through their efforts instead of your own. Potential end-users/customers are equally important although you’ll have a tougher time trying to determine their level of interest in your website/product.
Yes, you can use keywords to track tweets and find prospects on Twitter directories but interacting with each and every prospect (there are thousands out there) takes a lot of time and energy. I would prefer networking with influencers who can promote my site/brand in and outside of Twitter because they have a built-in audience and a platform.
Mass following can get you followers. But it doesn’t drastically improve your reputation, no matter how attractive a high follower count looks. A mass follower tweeting out a link is very different from an authority in the field endorsing a link by putting it in a tweet. The influencer is followed by a targeted list of other taste-makers.
The core of influence will spiral outwards based on the initial endorsement. This is more powerful than a link sent out to an auto-follow audience. Sure, you can easily get traffic but your tweets are not as effective as a voice that is respected by your target market.
So who should you network with? Not just end-users with your keyword in their bio. But bloggers, webmasters, publishers, journalists and business owners. People who work in your field and own web sites that can send you links and traffic. You can focus on networking with the superstars in your field but don’t ever forget about less famous people. This article by Brett Borders offers a good explanation of why you shouldn’t ignore the average Twitter user.
So in essence, you should use Twitter as a relationship building tool to extract benefits from a core group of influencers who are relevant to your business/website. Network actively with the right Twitter users, talk to them, spread their links, give them feedback, support their content. Be a participant in their Twitter experience.
If you do this long enough, you will eventually make them comfortable with helping you or promoting your stuff either on Twitter or away from it.
If someone talks to me very often on Twitter, shares my content or points me to good resources, I’m more than willing to retweet their stuff. Especially if its great content. I wouldn’t think twice about it. The desire to reciprocate is a very powerful instinct.

Image Credit: Erica_Marshall
And if you want to talk about ‘going viral’, just a few retweets from several users with responsive audiences and your link will get all the momentum it needs. You don’t need to build up an account with tens of thousands of users only to send your message out to people who aren’t even half-interested in your content.
You will gradually grow your business or website by getting more readers, clients or buyers through the help of that core group. And after you’ve achieved some success, people will naturally start to follow you on Twitter. And these are the best kinds of Twitter followers to have, people who opt-in because they are interested in you or your work.
Then you can concentrate on these new batch of followers and by interacting with them, turn them into people who will actively support your content or initiatives. Many of them might be site owners or bloggers as well so this is a great way to network and learn if you’re looking for some help to improve your core business offerings.
In terms of making money indirectly or directly through Twitter, I’ve realized that the no. of Twitter followers you have is not always proportional to the income you’ll make.
It’s not necessary to inflate your Twitter follow count through an automated game of mass following. But I understand why people do it. It’s the same old strategy used on Myspace, Facebook and pretty much any social site where people can ‘friend’ each other and capture attention. The mentality is go for maximum volume and hook the few that will listen.
You can go down that route if you want but I think you can easily achieve the same results and more by cultivating a high quality list of followers and networking smartly with the right people. Marketing on Twitter does not just involve getting as many followers as you can.
Think beyond that. If you want followers, you should get them to come to you. You don’t have to chase after them. It’s devastatingly easy once you learn how to leverage other users with established audiences and create bait that entices people to opt-in because of interest.
What do you think? Feel free to leave a comment below or talk to me on Twitter!
Twitter Marketing: Why You Don’t Need to Mass Follow Users
OpenRasta, an open source alternative for developing Restful services
OpenRasta (OR) is the name of a new open source framework for developing Restful applications (Web applications or services) created by Sebastien Lambla. As the ASP.NET MVC, this framework is also an implementation of the MVC pattern, which focus mainly on a good separation of concerns, and provide different extensibility points where the developer can plugging custom code at the moment of developing applications.
The framework is now on Beta 2 stage, Sebastien and other guys are currently working on improving the hosting infrastructure and public API. They are, of course, very open at this point to receive feedback or suggestions for new features, or improvements to existing ones. If you have some interest in participating of this project, you can start joining the mailing list.
In order to understand how OR works under the hood, I will start by describing some basic concepts that a developer should know to implement an application from scratch with this framework.
Handlers
A “handler” is one of the main building blocks in OR. It represents the implementation of the service itself, and it is generally mapped to single resource through an URI. Therefore, any access to an URI will get resolved by OR to an specific handler.
From an implementation point of view, a handler is simple class that expose methods for handling different http verbs. By convention, a method should be called as the Http verb that supports, for example, Get or Post. However, nothing prevent you from giving more friendly names to the methods (or handler operations), there is an special custom attribute “HttpOperationAttribute” that you can use to associate the method with an http verb.
public class CustomerHandler
{
public Customer Get(int customerId)
{
return new Customer { FirstName = "foo", LastName = "bar" };
}
public OperationResult Put(int id, Customer customer)
{
return new OperationResult.Modified { ResponseResource = customer };
}
[HttpOperation(HttpMethod.POST)]
public OperationResult MyFriendlyMethod(int id, Customer customer)
{
return new OperationResult.Modified { ResponseResource = customer };
}
}
If you want to have a better control of the Http status code, as it is shown in the code above, you can also return an instance of OperationResult.
Codecs
As you can see, the handlers have not been wired to any content type at this point. Serializing/Deserializing a resource instance into an specific representation is responsibility of the codecs. Some codecs are provided out of the box in OR, for example, Json, Xml, Html or Form-Url-Encoded data.
A codec generally implement two interfaces, IMediaTypeReader (for deserializing content) and IMediaTypeWriter(for serializing). The following code shows the implementation of the Json codec,
[MediaType("application/json;q=0.5", "json")]
public class JsonDataContractCodec : IMediaTypeReader, IMediaTypeWriter
{
public object Configuration { get; set; }
public object ReadFrom(IHttpEntity request, System.Type destinationType, string paramName)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(destinationType);
return serializer.ReadObject(request.Stream);
}
public void WriteTo(object entity, IHttpEntity response, string[] paramneters)
{
if (entity == null)
return;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(entity.GetType());
serializer.WriteObject(response.Stream, entity);
}
}
Putting Handlers and Codecs together
By means of a fluent configuration, we can later wire up an URI with the corresponding handler and one or more codecs according to the content-types that the service should support.
ConfigureServer(() => ResourceSpace.Has.ResourcesOfType<Customer>()
.AtUri("/customer/{id}")
.HandledBy<CustomerHandler>()
.AndTranscodedBy<OpenRasta.Codecs.JsonDataContractCodec>()
.AndBy<OpenRasta.Codecs.XmlSerializerCodec>());
This is one of the big differences with the ASP.NET MVC or the Web Programming Model in WCF.
In the MVC, the supported content types are inherently tied to the ActionResult returned by the controller action. Therefore, the action implementation must be modified in order to support new content types. Or a more specialized implementation of an ActionResult is required, which has to be smart enough to accommodate these changes.
Same thing happens with WCF, you have to either decorate the service operation with the supported content-type (Only Json or Pox supported today) or return a Message/Stream instance from the operation and write the resource representation yourself in the operation implementation. As I said, only Json/Pox are supported today, and adding new content types is something complicated to do. You basically need to write a custom IDispatchMessageFormatter extension, and a custom WebServiceHost to replace the formatter provided out of the box. (This is the approach taken in the WCF REST Starter kit for supporting form-url-encoded data).
Pipeline Contributors
Let’s go back to OpenRasta for a moment, “Handlers” and “Codecs” are not the only supported extensibility points in this framework. All the processing of incoming/outgoing messages is performed in a pipeline that contains contributors or filters. A pipeline contributor perform simple tasks such as initializing the security context, routing the messages or processing exceptions to name a few. You can write your own contributors, or customize the pipeline to support different configurations or scenarios
More information about OpenRasta
You can find more information about this framework in the Sebastien’s blog. The current project status is also available here.
AJAX update content every X seconds
I was asked several times on Twitter how to update some web page section or a block content on a page every x seconds. Some real life examples of this functionality are Twitter search results that come out when there are new tweets with search keyword or bit.ly real time link tracking that updates it’s charts every 5 seconds. It is clear without saying that we are going to update our pageDeveloping RESTful services with JSON and POX support in the ASP.NET MVC
Many of the features available out of the box today in the ASP.NET MVC framework are only intended to develop web applications using REST principles. There is not support for accepting incoming messages encoded as JSON or plain old XML (POX), or even support for returning POX from a controller action. Only form-urlencoded data is accepted by default for incoming messages, and JSON/HTML (with support of the view engines) for outgoing messages in controller actions.
However, thanks to the different extensibility points that the MVC provides for hooking up custom code, supporting different scenarios for RESTful services tend to be something really easy to implement.
In this framework, we basically have two extensibility points that deserve some attention, Action Filters and Action Results.
Action filters intercept messages before they are dispatched to the controller action (or operation), and just after the operation returns a result. They are basically equivalent to the Dispatch Message Interceptors in WCF, or the new Message Interceptors in the WCF REST Starter kit (although they work more at a deeper level in the WCF processing pipeline).
Action results know how to serialize and write an object (the controller action result) into the response stream. Since they also have access to the Response object, additional work can be done there to manipulate some response settings or add output headers.
The framework also support Model Binders, which basically knows how to create an object representing the model expected by the controller action from some scalar values. Those scalar values are parsed from the incoming message (encoded as form-urlencoded), and then passed to the binder. However, they do not seem to add any value for implementing RESTful services with support for JSON or XML.
Omar Al Zabir has already written an nice post on how to implement RESTful services with the ASP.NET MVC that speak JSON and XML using action filters and action results.
ATOM and other syndication formats can also be handled as XML. For this, the Web Programming Model in WCF comes with a couple of classes, Rss20FeedFormatter and Atom10FeedFormator, which are Data Contracts and also IXmlSerializable classes. Therefore, if your operation returns an instance of any of these classes, the filters created by Omar would address this scenario as well. Regarding Conditional get support, you will have to implement it in the action itself or a custom filter. (You will have to do the same thing if you decide to go with the WCF Web Programming Model).
Caching is another feature that you might want to use at the moment of developing RESTful services. Fortunately, the MVC also comes with an special action filter “OutputCache” that was built on top the ASP.NET cache, so it provides the same caching capabilities that you may use for normal ASP.NET pages.

