Ajax Widgets with ASP.NET MVC Preview 3
Since some time ago I’ve been working with ASP.NET MVC in a project for InSTEDD. The whole project includes quite a lot infrastructure (e.g.: little MVC projects that are plug-ins of the main website), but in this post I will try to show the approach we choose to accomplish Ajax Widgets that are governed by a controller. The design was also though to have a good developer experience (this mainly defines the signature of the ViewUserControls that represents the desired widgets). Also, two other goal were achieved, a) the first load of the page includes the widget rendering (so the user doesn’t need to wait longer than the main page loads), b) it is easy to notify the user about some actions: information, warnings and errors messages regarding the last action performed.
I’ve prepared a sample tagging application that runs with an in-memory storage. I will describe how the application works as a guidance for this post.
As you would expect I have an ItemsController which decides the Items to show (but only the items, not the tags).

A simple List view implementation for displaying the items would be as follows:

If now we want to add Tagging capability to this view, what should be developed? a) the View for displaying tags of each item, and b) a Controller to both perform actions and render the updated view.
Since in the List view of items the model are just items, without tags, to keep the view markup simple, and be easy to include the Tags Edit widget in any part an item is displayed the widget should inherit from ViewUserControl<Item>. (actually I’ve develop a base class for widgets: MvcWidget which I will introduce later). So, the final version of List view is as follows:

But if the Tags Edit widget has just an Item as model, how does the tags come from? Every ViewUserControl has a reference to the Controller through the ViewUserControl.ViewContext property. So we decide that the TagsController which will be the ajax endpoint, also is responsible for augmenting the Item with the list of tags. So the markup of the Tags Edit widget would be something like this:
I didn’t show the full source here to be more clear in the presentation (in the downloadable file the solution is complete of course). As you could see in the tooltip, the new Controller property of the view is strongly typed as TagsController. The view base class did that:
The final result will be that the root div (with class UpdatePanel) will be replaced upon an ajax request to the server. This could be done with your favorite JavaScript library (jQuery is mine). I’ve done some helper functions to treat link navigation and form submit to ajax request and perform UI update as needed.
A minimal TagsController implementation would be something like this:
Upon ajax request, Add and Remove methods will perform the appropriate actions in Repository and then Renders the Tags Edit view with an Item as a model, without tags, the same controller instance will be used to retrieve the tags for the item.
For the first load, we don’t have a TagsController instance, since the request was processed by a ItemsController. The MvcWidget class simply instantiate a TagsController for this case (of course, you should plug your DI framework here).
This depicts mostly the main design. To provide feedback to the user regarding the last action I implement two new kinds of ActionResult.
- JavaScriptActionResult which renders a <script type=”text/javascript>…</script> element with a specified scripts.
- CompositeActionResult which completes the ActionResult type hierarchy to implement a Composite pattern.
Also, ad-hoc for the site I implement ClientStatusActionResult which inherits from JavaScriptActionResult to have a nicer controller code. An implementation without error handling of the Add method could be like this:
I suggest to look at the downloadable source to get a better implementation with error handling. For example, the repository may throw an exception when the maximum amount of tags is exceeded, in this scenario a ClientStatusActionResult with ClientStatus.Error is returned in composition with the Tag Edit view as was submitted from the user.
BatchResults method is just a Controller extension method that returns a CompositeActionResult for the given argumetns.
jQuery runs the script element when it arrives from the server, so the JavaScript that update the status DOM element is execute.
A final note, the whole idea and implementation was a result of some pairing sessions with Juan Wajnerman.
Any kind of feedback is welcomed!
My first conference at microsoft argentina
You can register for the event here. Thanks Miguel for this opportunity.
event details (spanish):
Towebs & MSDN lo invitan a conocer las herramientas más innovadoras para el desarrollo web en plataforma Windows. Las charlas, están orientadas a programadores y desarrolladores. Queremos brindarle la posibilidad de que sus sitios web se diferencien del resto. Para lograrlo lo invitamos a capacitarse en el uso de tecnologías de última generación como ASP.NET, AJAX y Silverlight.
Fecha: Jueves, 5 de Junio
|
Inicio |
Presentación |
Orador |
|
14:00 |
Acreditación |
|
|
14:30 |
Introducción a desarrollo web en .NET |
Miguel Sáez |
|
14:55 |
Acceso a Datos en .NET |
Miguel Sáez & Pablo Listingart |
|
15:40 |
Intervalo |
|
|
16:00 |
Creando aplicaciones AJAX con ASP.NET |
Brian Cardiff & Miguel Sáez |
|
17:00 |
Creando aplicaciones RIA ( Rich Interface Applications) |
Martin Salias |
|
17:30
|
Fin del evento |
|
Improved argument matchers in Moq
The new feature encapsulated by MatcherAttibute in Moq allows developers to create quite easy argument matchers.
In a scenario with a Customer class and a IFooService:
public class Customer { public string Name { get; set; } public int Age { get; set; } // … } public interface IFooService { void Bar(Customer c); }
If in a test you need an expectation on Bar method that stands for a Customer c where c.Age >= 18 you
needed to do something like this:
[Test] public void Test1() { var mock = new Mock<IFooService>(MockBehavior.Strict); mock.Expect(x => x.Bar(It.Is<Customer>(c => c.Age >= 18))); // … }
but from now on, using the MatcherAttribute the same expectation could be written as follows:
[Test] public void Test1() { var mock = new Mock<IFooService>(MockBehavior.Strict); mock.Expect(x => x.Bar(GrownUp())); // … } [Matcher] public static Customer GrownUp() { return null; } public static bool GrownUp(Customer c) { return c.Age >= 18; }
Lets call the first GrownUp method as Matcher declaration, and the second Matcher implementation.
- Matcher declaration must has return type Customer in order to allow the expectation to compile, and be applied the MatcherAttribute.
- Matcher implementation is used in the actual match, receiving the Customer to be matched and returning the result of the match.
- Matcher declaration is never executed by Moq, it is used to have clear syntax.
More arguments
Also you could have more arguments involved in the matching, just add the at the end of both declaration and implementation.
For example to match older than a certain age:
[Test] public void Test1() { var mock = new Mock<IFooService>(MockBehavior.Strict); mock.Expect(x => x.Bar(OlderThan(18))); // … } [Matcher] public static Customer OlderThan(int minimumAge) { return null; } public static bool OlderThan(Customer c, int minimumAge) { return c.Age >= minimumAge; }
Your own helper class
To reuse some matchers, you could define them in a separate a class instead of inside the fixture.
[Test] public void Test1() { var mock = new Mock<IFooService>(MockBehavior.Strict); mock.Expect(x => x.Bar(An.OlderThan(18))); // … } static class An { [Matcher] public static Customer OlderThan(int minimumAge) { return null; } public static bool OlderThan(Customer c, int minimumAge) { return c.Age >= minimumAge; } }
Non static method
Finally, the matchers declaration and implementation don’t need to be static. So you could have additional context of matching.
Although I suggest this last only in certain scenarios, for example, match enumeration of values:
[Test] public void Test2() { var mock = new Mock<IFooService>(MockBehavior.Strict); var names = new E(new [] { “John Doe”, “Brian Cardiff” }); mock.Expect(x => x.Bar(names.Some())); // this will success // mock.Object.Bar(new Customer { Name = “Brian Cardiff” }); // this will fail // mock.Object.Bar(new Customer { Name = “Sandy” }); } public class E { IEnumerable<string> names; public E(IEnumerable<string> names) { this.names = names; } [Matcher] public Customer Some() { return null; } public bool Some(Customer s) { return names.Contains(s.Name); } }
Upgraded jQuery Tag Suggestions
Yesterday remy sharp update jQuert Tag Suggestions plugin a list of fixes can be found here.
The new features are really good:
- Be able to use multi words tags by specifying the separator. (my contribution)
- Added filtering to prevent already selected tags appearing in the suggestions.
Some plugins are really nice….
GuardQ: Guard class meets Linq
In the task of validating function arguments, usually a sealed class Guard is created. For example, if we want to validate for null value the usual code is:
public sealed class Guard
{
public static void ArgumentNotNull(object val, string argName)
{
if (val == null)
throw new ArgumentNullException(argName);
}
}
public class Bank
{
public void Transfer(Account source, Account destination, decimal amount)
{
Guard.ArgumentNotNull(source, "source");
Guard.ArgumentNotNull(destination, "destination");
// TODO ... actual founds transfer
}
}
I never like to pass the parameter and it’s name in the same argument call, specially because while refactoring, the argName argument won’t be changed by default.
To eliminate that hack, we could use GuardQ (C# 3.0), which will be consumed, for the same example of above as:
public sealed class GuardQ
{
public static void ArgumentNotNull<TResult>(Expression<Func<TResult>> expression)
{
if (expression.Compile().Invoke() == null)
{
PrettyPrinter printer = new PrettyPrinter();
string argName = printer.Print(expression.Body);
throw new ArgumentNullException(argName);
}
}
}
public class Bank
{
public void Transfer(Account source, Account destination, decimal amount)
{
GuardQ.ArgumentNotNull(() => source);
GuardQ.ArgumentNotNull(() => destination);
// TODO ... actual founds transfer
}
}
Only one argument per validation: a lambda expression with no parameters and the parameter to validate in the body. From the expression’s body, using a kind of ExpressionPrinter we could get the argument name: hack removed!. And refactoring is 100% supported.
Since the ToString method of the body of () => source, would return something like “value(GuardQ.Tests.Demo+Bank+<>c__DisplayClass0).source”, I start to develop a PrettyPrinter, to get a string representation of the expression that the user input in the source code (currently, don’t printing the context nodes).In the following weeks some additions will appear, and a non-spike code would be available in MoQ.
Current source: https://moq.googlecode.com/svn/spikes/GuardQ/
Build Xml files in Ruby
If you have to generate xml in ruby I suggest take a look at builder gems. It has really little overhead to generate xml. Take a look to this example:
require 'Builder'
xm = Builder::XmlMarkup.new( :target => $stdout , :indent => 2 )
xm.instruct!
xm.people do | p |
p.person(:firstname => "brian", :lastname => "cardiff") do | a |
a.cdata!("it's me!")
end
p.person(:firstname => "ary", :lastname => "borenszweig")
end
will print in stdout
<people>
<person lastname="cardiff" firstname="brian">
<!--[CDATA[it's me!]]–>
</person>
<person lastname=”borenszweig” firstname=”ary” />
</people>
the target parameter could be a string or file (or anything with << method).
self.begin
OK, let see how this evolves. Hope to start blogging regarding my main interests topics (list here).
