Information Overload

by Rasmus Kromann-Larsen November 17, 2008 18:26

Ran into this at work today. Apparently our Team Foundation Server wanted to tell me something.

image

I'm still not sure that I pressed the right button - what does Cancel do again?

kick it on DotNetKicks.com

Tags: ,

Patterns: Iterator And .NET - Yield I Say!

by Rasmus Kromann-Larsen November 11, 2008 23:24

Introduction

In this second post of my patterns and principles series, I aim to give an overview of the Iterator pattern, a pattern most of us .NET people have so integrated in our languages that we don't even think about it. But it is still useful to know the theory of the pattern and how it is integrated into the framework - the solution baked in allows for more variation than you'd think.

The Theory

According to Gang of Four, the Iterator pattern's intent is to:

Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation.

Basically what we want to do is abstract the traversal so we don't have to worry about it. The Iterator will provide us with a nice interface for getting the next object in our data structure, maintain state about how far we've already progressed in our traversal and tell us when we're done. Abstracting the traversal also makes it easier to change the actual traversal - like if you want to iterate over your data structure in reverse order.

Furthermore, encapsulating the traversal logic in an Iterator will often result in higher cohesion and lower coupling for client code. Higher cohesion because they can more clearly express their intent instead of worrying about iteration state and order - and lower coupling because they are not as tied to the actual implementation of the data structure being iterated. As a result, it is possible with Iterators to provide a uniform interface for traversing different data structures.

Iterators are also sometimes used as Generators, where they generate a series of values instead of actually iterating over an object structure. If implemented lazily, these can generate potentially infinite series like a never-ending stream of numbers or primes or whatever.

How Does It Work In .NET?

One of the reasons we rarely think about the Iterator pattern is because it's so embedded into our languages. In the .NET world, an Iterator is actually called an Enumerator - and if we look in the framework documentation, we find an interface named IEnumerator that looks something like this (the generic version):

public interface IEnumerator<T>
{
	bool MoveNext();
	void Reset();
	T Current { get; }
}

This looks a lot like the abstraction described in the Gang of Four book. But how often do you actually see the IEnumerator interface in your code - not too often I bet. This is because the pattern is even more tightly integrated into the framework. Digging deeper, we find the IEnumerable interface which looks like this:

public interface IEnumerable<T>
{
	IEnumerator<T> GetEnumerator();
}

So any class that implements the IEnumerable interface is able to supply you with an Iterator. Lots of classes in the .NET framework implement IEnumerable - and a naive usage of it might look something like this:

void NaiveEnumeration()
{
	var list = new ArrayList<int> { 1, 2, 3, 4, 5 };
	
	var enumerator = list.GetEnumerator();

	while(enumerator.MoveNext()) 
	{
		var number = enumerator.Current;
		Console.WriteLine(number);
	}
}

But iteration is something we do often - and the pattern has even mandated its own keyword - foreach - so when you go like this:

void NormalEnumeration()
{
	var list = new ArrayList<int> { 1, 2, 3, 4, 5 };
	
	foreach(var number in list)
	{
		Console.WriteLine(number);
	}
}

You're actually using the IEnumerable and IEnumerator interfaces, you just don't see them. Simply put, foreach is really just syntactic sugar for the above construction - conceptually at least.

But this isn't all. Since C# 2.0, there has also been the yield keyword. Yield can be somewhat tricky to wrap your head around at first, but once you've used it a few times, you really appreciate the power of it. It provides a nice and clean way of implementing the Iterator pattern without worrying too much about managing state. It basically allows you to point out values have the framework create an Iterator for you. The reason it can be somewhat confusing is that it messes with the normal semantics of executing a method. Lets take an example:

IEnumerable<int> GetNumbers()
{
	var number = 1;

	while(true)
	{
		yield return number;
		number += 1;
	}
}

At first sight, this method looks kind of broken. Notice that the function returns an IEnumerable - that is: an object that provides an IEnumerator. The IEnumerator is created for us behind the scenes and whenever it encounters your yield return statement, it "freezes" your method and returns this value. When MoveNext is called the next time (explicitly or through a foreach loop), the code picks up exactly where it stopped last time - in this case adding 1 to number and yielding once again. Note that even though this code won't loop forever when creating the Iterator, a foreach statement using GetNumbers will - as expected.

There's also a yield break statement that you can use when implementing an Iterator with yield - it just returns nothing and stops the iteration, much like the break statement in a for loop.

Variation Point (And More .NET)

As with most patterns, the Iterator has variation points. One of the variation points in the Iterator pattern is who controls the iteration. Gang of Four distinguishes between an internal iterator and an external iterator.

With an external iterator the client of the iterator has the responsibility for advancing the iterator explicitly and to request the item that is being processed. The examples we saw above using the various constructs are all examples of external iterators.

An internal iterator on the other hand is more declarative, with an internal iterator, we actually don't see the iterator itself, but we provide an operation to be performed on the iterated elements. An example of this is the ForEach method defined on List<T>. This allows you to pass a delegate that is to be executed on each element in the list. In C# 3.0, using lambdas the above could look something like this:

void InternalEnumeration()
{
	var list = new ArrayList<int> { 1, 2, 3, 4, 5 };
	
	list.ForEach(number => Console.WriteLine(number));
}

In this case we no longer control the iterator and can't stop after 2 elements if that's what we wanted.

Considering LINQ in this light is left as an exercise to the reader.

Conclusion

In this post I've given a short introduction to the Iterator pattern and shown how we use it every day without even thinking about it. But they can be used for much more than our every day scenario iterating over already made collections. And be sure to play around with the yield statement.

kick it on DotNetKicks.com

Tags: , , ,

Design Patterns

Design By Contract Preconditions With Expression Trees

by Rasmus Kromann-Larsen November 06, 2008 23:58

Introduction

Seems like Design by Contract is coming to C# 4.0, replacing the somewhat inadequate Debug.Assert, which is the only thing built into the framework at the moment. However, what are the options for today? In this post, I'll take a look at how to improve current precondition checking techniques using C# 3.0 expression trees.

Design By What?

Design by contract is technique for strengthening the contracts for classes by adding 3 kinds of checks:

  • Preconditions - What the called method expects from the caller. This is usually various forms of checks on method arguments.
  • Postconditions - What the called method guarantees upon returning. Often guarantees about the return value.
  • Invariants - What is guaranteed by the class? That is, the class invariant should be true upon one of the objects methods and again when the method returns.

So why is this even important? One of the merits of Design by Contract are that it can communicate a whole lot about your classes to other people using or reading your code. but they can also be helpful to you, as they allow you to express your intent more clearly and will support the fail-fast principle of defensive programming. The idea here is to produce the error as close to the source as possible.

Lets do a simple example to illustrate why this might be useful, consider the following two classes:

public class Person
{
    public Person(string name)
    {
        Name = name;
    }

    public string Name { get; set; }
}

public class Account
{
    private Person _owner;

    public Account(Person owner)
    {
        _owner = owner;
    }

    public string GetOwnerName()
    {
        return _owner.Name;
    }
}

It seems that the writer of the Account class is implying that an Account object should have an owner - an instance of Person. However, there's nothing to stop a potential client from doing this:

static void Main(string[] args)
 {
     var account = new Account(null);
     Console.WriteLine(account.GetOwnerName());
 }

This fails with a NullReferenceException in line 4 with the following stack trace:

DbCExpressionTrees.exe!DbCExpressionTrees.Account.GetOwnerName() Line 17	C#
DbCExpressionTrees.exe!DbCExpressionTrees.Program.Main(string[] args = {string[0]}) Line 13 + 0xa bytes	C#

Now this example is very contrived, since it's blatantly obvious where the bug is. But still, consider if the call to GetOwnerName had been in a completely different layer of the application, maybe even minutes after the Account object had been created. I'm sure you've had your fun with your debugger tracking down errors like this, if you've done any moderate size programs - I know I have.

What we need is a way for the writer of the Account class to communicate a stronger contract on what he's expecting from his client. In an ideal world, this contract would be enforced at compile-time and not allow the program to compile if contracts were broken. A thing I've always wanted for situations like this is being able to specify arguments as non-nullable in C# - that is, give me an object of this type and NOT null - since this makes sense in a lot of situations. Anyway, the only way to get something resembling this today is using Spec#, but this is a research project and still under development. So we will have to settle for runtime checks for starters.

Returning to the fail-fast principle - why is this useful? Consider the following change to the Account constructor:

public Account(Person owner)
{
    if(owner == null)
        throw new ArgumentNullException("owner");

    _owner = owner;
}

Executing the client code from before, our program will now fail when trying to create the invalid Account object with the following stack trace - and a clearly readable exception message (that owner is not allowed to be null):

DbCExpressionTrees.exe!DbCExpressionTrees.Account.Account(DbCExpressionTrees.Person owner = null) Line 13	C#
DbCExpressionTrees.exe!DbCExpressionTrees.Program.Main(string[] args = {string[0]}) Line 12 + 0x17 bytes	C#

The benefit here is that this stack trace points directly to the first offense against the "contract". Consider the differences in debugging time on the two examples. Examples like this could also be made for postconditions and invariants.

Expression Trees

Okay, I admit it, I've been itching to play around with Expressions since C# 3.0 was released and especially with all the cool usages in ASP.NET MVC. Furthermore I'll often go to great lengths to avoid "magic strings" in favor of something more type-safe (and refactor-friendly). Also, I happened to stumble upon these two posts by The Wandering Glitchand Søren Skovsbøll where they experiment with Design By Contract and C# 3.0.

Realistically, I preconditions are only viable part of Design by Contract to implement in C# at the moment. While you can probably do crazy postcondition and invariant checking by using exotic things like IL injection or interceptors, I really don't think we'll see any really good solutions until the language provides better support. So I decided to see what I could do on preconditions.

Now, Søren and Andrew (the Glitch) used a general Requires method for defining their preconditions. Søren's looks like this:

public static void Require(this T obj,
	Expression<Func<bool>> booleanExpression)
{
   var compiledPredicate = booleanExpression.Compile();
   if (!compiledPredicate())
      throw new ContractViolationException(
         “Violation of precondition: ”
         + booleanExpression.ToNiceString());
}

When using a lambda wrapped in an expression, we don't get the delegate that we're used to, instead we get something that resembles an abstract syntax tree that represents the expression. This is what enables us to pull various information about the expression. As shown above, the expression can then be compiled into the delegate that we're used to and executed.

However, compiling expressions is not the cheapest operation ever - and I personally believe that it can be beneficial to leave your contracts (if they are runtime) in your production code. Since breaking the contracts in production could lead to undefined behavior (or at least unintended), it would be nice to find the offender easily from the log containing the stack trace. So, since we're most likely going to use preconditions many places, it'd be super nice if they were as fast as possible. But preferably still without the strings.

My preference so far has been to do specialized methods for checking various things. If we have very specific methods for checking stuff the occurs often, we can make assumptions (or requirements) about the format of the lambda expressions and cut out the expression compilation. For more exotic things I'll still use the Requires method as shown above.

The example I'll show here is the same I did in my example earlier namely checking method arguments for null. This is arguably the precondition seen most often - however I've also done others checking arguments for empty strings in much the same way.

My ArgumentNotNull method defined on my static Check class looks like this:

public static void ArgumentNotNull<T>(
     Expression<Func<T>> argumentExpression) where T : class
{
    var memberExp = argumentExpression.Body as MemberExpression;

    if (memberExp == null)
        throw new ArgumentException
           ("Invalid Contract: ArgumentExpression "+ 
             "was not a MemberExpression.");

    var constantExpression = memberExp.Expression as ConstantExpression;

    if (constantExpression == null)
        throw new ArgumentException
          ("Invalid Contract: ArgumentExpression didn't "+
           "contain a ConstantExpression.");

    // Argument will be a field on the class.
    var fieldInfo = memberExp.Member as FieldInfo;
    // The contant expression will contain the object we're 
    // calling from.
    var methodOwner = constantExpression.Value;

    // Use the fieldInfo to extract the information directly from the owner
    if (fieldInfo != null && fieldInfo.GetValue(methodOwner) == null)
        throw new ArgumentNullException(memberExp.Member.Name);
}

The use in the Account class will look like this:

public Account(Person owner)
{
    Check.ArgumentNotNull(() => owner);
    _owner = owner;
}

and it will throw an exception that looks exactly like the one in my first example, so all the expression / reflection magic was really just to extract the argument name in a type-safe way. The ArgumentNotNull expects only lambda expressions containing a single argument and can thus make assumptions on the generated expression and pull the field value directly from the correct instance without compiling the expression.

But writing these specialized methods takes longer time and the Requires method can capture infinitely more conditions - so is this really worth it performance-wise? I did a small micro-benchmark - note: I've focused on the scenario where there's no error, since it by far the most common occurrence - we don't really care about performance if we're killing the program with an exception.

static void Main(string[] args)
{
    var timerArgumentNotNull = new Stopwatch();
    var timerRequires = new Stopwatch();
    var obj = new object();

    timerArgumentNotNull.Start();

    for (var i = 0; i < 10000; i++)
        TestMethod(obj);

    timerArgumentNotNull.Stop();

    timerRequires.Start();

    for (var i = 0; i < 10000; i++)
        TestMethodWithRequire(obj);

    timerRequires.Stop();

    Console.WriteLine("Argument not null: {0}", 
		timerArgumentNotNull.ElapsedMilliseconds);
    Console.WriteLine("Requires not null: {0}", 
		timerRequires.ElapsedMilliseconds);

    Console.ReadKey();
}


private static void TestMethod(Object obj)
{
    Check.ArgumentNotNull(() => obj);
}

private static void TestMethodWithRequire(Object obj)
{
    Check.Requires(() => obj != null);
}

And the results were as follows:

image

Now the Requires function could probably be optimized (maybe some expression caching), but the difference is quite remarkable.

Conclusion

In this post I've described some of the benefits with Design By Contract and defensive programming and tried to give some insight into using C# 3.0 Expression Trees for avoiding "magic strings" in our precondition checking.

kick it on DotNetKicks.com

Tags: , , , , ,

Development

Simple ASP.NET MVC Beta AJAX with jQuery!

by Rasmus Kromann-Larsen November 05, 2008 21:23

Introduction

ASP.NET MVC is all the rage these days - and after Microsoft announced their partnership with the great folks over at jQuery and started shipping it - I knew I had to explore the whole AJAX experience again. I've still not played too much with the MVC framework, but I am working on switching a few projects over from WebForms - and I must say that the experience is quite different. So I've set out to do the smallest (simple) demo possible of ASP.NET MVC AJAX with jQuery - just to get (and give you) the flavor of it.

The Story

I did play around with the Microsoft AJAX Library earlier, but found it too heavy-weight and never really liked the concept of UpdatePanels. It just seemed like too much server-side cruft and coupled with the rather complex WebForm lifecycle, it just didn't seem worth it. I must admit that this is a while ago and I haven't reinvestigated, but I doubt it has the grace and simplicity of jQuery. So I've been using jQuery since forever for various client-side snippets, but never really played around with the AJAX bits since it seemed kind of cumbersome with WebForms.

Lets Get Started

Okay, so I grabbed the beta bits from the ASP.NET MVC and installed them on my machine and fired up a new ASP.NET MVC site:

image

The solution now already contains a "Scripts" folder that contains Microsoft AJAX and jQuery. Continued to head into the Site.Master masterpage in Views/Shared to add jQuery. Now I'd caught the glimpse of blog posts mentioning intellisense for jQuery and found this post describing how to grab the vsdoc version of jQuery from the jQuery site and plug it in.

image

Since this was just going to be a demo site, I decided to just use the documented version directly, but this proved to be a bad idea. I encountered a few different runtime JavaScript errors while using this version, more specifically related to the ajaxStart event function. The solution apparently involves a masterpage with the following added to the head section:

<% if (false) { %>
<script type="text/javascript" src="../../Scripts/jquery-1.2.6-vsdoc.js"></script>
<% } %>
<script type="text/javascript" src="../../Scripts/jquery-1.2.6.min.js"></script>

The trick here is that Visual Studio will see the vsdoc version and grab documentation from there, but it will never actually load on your pages. As described in the before mentioned post, this will be fixed and in the future it should be enough to reference the original jQuery file and have the vsdoc version present. I also found that the intellisense was kind of flaky (not showing up) sometimes in nested functions, hopefully this will be fixed as well.

Next I grabbed the Index.aspx view in Views/Home and cleared out all the contents of the Content PlaceHolder and added a bit of HTML:

<div>
    <input type="text" id="name" />
    <a href="#" id="link">Click me!</a>

    <div id="result" style="margin-top: 15px"></div>
</div>

This is just plain and simple HTML, with a "void" link that doesn't go anywhere. It looks like this:

image

Now one of the great forces about jQuery is it's power to hook into the DOM using powerful selectors. This means that you can have your JavaScript almost completely separated from your HTML. I've often had several small jQuery files that would completely change the appearance of a page and add all kinds of fancy if they were included. This also makes it very easy to enable / disable effects and even test your page degradation for users who have JavaScript disabled (just remove your script reference). However, for simplicity, I've just included my jQuery directly in a script tag:

<script type="text/javascript">

    $(document).ready(function() {
        // Register a click handler on our link
        $("#link").click(function() {
            // Perform a get with a callback of updateResult
            $.get("/Home/AjaxHtml", getName(), updateResult, "html");
        });

        // Extract name from textbox as associative array (JSON)
        function getName() {
            return { name: $("#name").val() };
        }

        // Append HTML to the result div
        function updateResult(html) {
            $("#result").append(html);
        }
    });

</script>

Now I decided not to start doing JavaScript templating and return lots of JSON data. Instead I'm just going to pull a normal HTML page from the HomeController and append the data to the result div. Most of the magic is in the click function which registers a handler to grab the defined page /Home/AjaxHtml with the name entered in the textbox as parameter and to execute the updateResult function when the data comes back. After this it was time to add the action to the HomeController:

public ActionResult AjaxHtml(string name)
{
    Thread.Sleep(3000);
    return View("AjaxHtml", new { Name=name, Time=DateTime.Now });
}

Rather simple really. Just sleeps for a few seconds (to allow me to see the load on my local dev machine) and then renders a new view called AjaxHtml with a simple Dictionary containing the passed argument name and the current time as ViewModel. I also added a new View called AjaxHtml:

<%@ Page Language="C#" AutoEventWireup="true" 
 CodeBehind="AjaxHtml.aspx.cs" 
 Inherits="MvcAjaxTest.Views.Home.AjaxHtml" %>
Ajax Call: <%= ViewData.Model %><br />

The only thing to note about this is that I didn't use my normal masterpage for this page - since I'm only interested in passing this little tidbit of HTML back - not my entire page layout. Launching the application again, typing a name and hitting the link produces the following without a full page reload:

image

Additional clicks append further AJAX lines like so:

image

Obviously this could have been some other information posted - but this little sample contains both information from client-side (the name) and some data appended by the server (the timestamp).

Load Indicator

Now, after doing all this, it didn't feel so impressive to click the link and wait for 3 seconds for another line of text to appear, so the obvious solution is to add some extra effects - and it's not like it's real AJAX [tm] if it ain't got a cool load indicator. So off I went to the kind people at ajaxload.info where you can customize your own animated gif load indicator. I went with the shape called "Snake" with a nice blue MVC template-like color.

Adding the load indicator was a breeze really. I just threw the load indicator in an invisible image after the link:

<div>
    <input type="text" id="name" />
    <a href="#" id="link">Click me!</a>
    <img id="loading" style="visibility: hidden" 
      src="../../Content/small-ajax.gif" />

    <div id="result" style="margin-top: 15px"></div>
</div>

Note that I used the CSS style visibility: hidden instead of using display: none. Both work, but when using display: none, the space for the image is not reserved on the page, which caused a small annoying "jump" effect on my page as the load indicator appeared (and was a few pixels taller than the link text). With the visibility style, space is actually reserved for the image and the line doesn't jump.

All we have left is hooking the load indicator onto jQuerys AJAX call - for a simple scenario like this, the global AJAX events called ajaxStart and ajaxStop are just what we need. ajaxStart will run whenever an AJAX request is started and ajaxStop will run whenever one ends. So at the end of my script block (after the updateResult function), I added the following:

$("#loading").ajaxStart(function() { $(this).css("visibility", "visible"); });
$("#loading").ajaxStop(function() { $(this).css("visibility", "hidden"); });

If we had used display: none instead, we could have used the jQuery functions show() and hide() instead of the whole CSS stunt, but I like this better. Firing up the browser and hitting the link now produces enough eye candy to distract my eyes from the 3 second wait:

image 

 

Resources

Now this is definitely only a beginning. You'd want to do some proper error handling and probably some more advanced scenarios.

If you want to find more information on ASP.NET MVC, you definitely want to go read / subscribe to some of these blogs: ScottGu, Phil Haack, Rob Conery (especially the Storefront series), Stephen Walther and many more.

As for more jQuery, there's been a storm of posts about this lately, which should be easy to find, but for documentation, nothing beats the plain ol' jQuery documentation or a personal favorite of mine for quick access: visual jQuery, a jQuery-optimized version of the jQuery docs.

Conclusion

In this post I gave a quick introduction to the world of AJAX using jQuery with ASP.NET MVC. I really enjoy the model and simplicity. It just feels right - and finally I have control over my HTML. Hope it was useful for you as well.

kick it on DotNetKicks.com

Tags: , , ,

ASP.NET MVC | jQuery

Powered by BlogEngine.NET 1.6.1.0
Theme by Mads Kristensen | Modified by Mooglegiant | Adjusted by Rasmus Kromann-Larsen

About Me

I am a danish .NET developer blogging about the technical side of my life, mostly .NET stuff, but also fundamental topics like design patterns, principles and productivity boosters.

In addition, I am a core group member of Aarhus .NET User Group.