Monthly Archives: January 2011

ASP.NET MVC and Razor View Engine Syntax

ASP.NET MVC 2 used the ASPX/WebForms view engine by default, which looks a little like this:

  <ul>
    <% foreach(var thing in stuffs) { %>
        <li><%: thing %></li>
    <% } %>
  </ul>

Code nuggets! That’s pretty painful to have to open and close nuggets all over the place. It begins to look like tag soup, especially with complex output.

So ASP.NET MVC 3 ships using the Razor view engine by default (you can still choose to use ASPX/WebForms if you like pain though). Here’s what Razor looks like to accomplish the same thing:

  <ul>
    @foreach(var thing in stuffs) {
        <li>@thing</li>
    }
  </ul>

That’s much better. With Razor, most things just work as you would expect. No entering and exiting code blocks are needed, and in the rare scenario that you need to escape things, it’s a simple matter of escaping with the ‘@’.

Dependency Injection

Today I’d like to talk about Dependency Injection.

Let’s first look at an example set of code:

public class Foo
{
    private Bar _bar;

    public Foo()
    {
        _bar = new Bar("Alpha", 123);
    }

    public void Baz()
    {
        _bar.Fire();
    }
}

The above example is a set of tightly coupled classes, in which Foo is completely dependant on the concrete Bar. This is not ideal, because a change to Bar will cascade into Foo due to the coupling. We also don’t have the option to change the dependency implementation; we must only use the concrete Bar.

How can we improve this?

public class Foo
{
    private Bar _bar;

    public Foo(string name, int number)
    {
        _bar = new Bar(name, number);
    }

    public void Baz()
    {
        _bar.Fire();
    }
}

Ok, that’s a little better, in that we can specify parameters to afford some flexibility, but it still doesn’t solve the original problem of depending on Bar’s concrete implementation. More improvement is needed.

public class Foo
{
    private IBar _bar;

    public Foo(IBar barRef)
    {
        _bar = barRef;
    }

    public void Baz()
    {
        _bar.Fire();
    }
}

That’s better.

Now we’ve altered our example such that the non-concrete IBar conforms to the functionality we expect, and we leverage it by having the caller be responsible for passing it to us; or in other words the dependency is injected. Now we can change the dependency, even at runtime if we choose, since Foo doesn’t care so long as it conforms to IBar.

This is a simplistic example of a pattern you can read more about:

Claims-Based Identity and WIF

Lately I’ve been researching claims-based identity with WIF, so I thought I’d share.

Claims-based identity is the notion that rather than having your application manage its own local credential storage, such as encrypted credentials, hash entries, etc, you will instead rely on an external provider. If you’ve ever read into how OpenID works, that is claims-based identity in practice. Your application, or “Relying Party” (RP) will not store credential information, but will rather trust the word of what a Security Token Service (STS) says about a user. The advantages of such a system is that you have a potentially wider set of authenticated individuals to service, and the risk and cost of having a local credential storage is eliminated.

Here’s how it works.

A user wants to authenticate on FooWebsite, so he clicks “log in”. FooWebsite does not implement a local credential store, but rather trusts that a STS called BarAuthenticator will ensure the user is authentic, and therefor redirects the user to BarAuthenticator to authenticate. The user then inputs his credentials (whatever that means to BarAuthenticator; because FooWebsite does not care about the particular implementation). Assuming BarAuthenticator STS is satisfied with the credentials, it will emit a token to the authenticating party (the user), which is digitally signed to prevent tampering. Contained in that token is a set of key-value pairs, which are collectively referred to as claims. A claim can be anything; It can be the user’s name, a role, a birthday, whatever. The user is then redirected back to the RP, FooWebsite, where his token is then given. If the token is verified to have originated from the trusted STS, the claims are accepted as truth, and the user is authenticated/authorized in whichever manner that the RP deems appropriate for the given claims.

The “Issuer” is our STS (Security Token Service), and the “Application” is our RP (Relying Party).

So where does Windows Identity Foundation fit in to this? WIF is the framework for .NET that abstracts the various components of such a system, including standing up an STS (if need be), and the entire authentication system described above. There is a set of decent video tutorials on the particulars of WIF on Channel 9 here.

Memoization

A coworker and I were recently discussing SDE interview questions, and I proposed that one of them could involve the use of memoization, which stores calculated values so they don’t need to be recalculated later. He hadn’t dealt with memoization much, so I wrote up two little sampler programs to demonstrate the value it can add. These programs calculate the Nth Fibonacci number, in the typical lazy recursive way (iterative could be better since it wouldn’t require all those stack frames, but this is just to prove a point).

First, here is the non-memoized form:

#include <iostream>

class Fibber
{
    private:
        std::map<unsigned int, double> _fibs;

    public:
        double fib_of(unsigned int idx)
        {
            if(idx <= 2)
            {
                return 1;
            }

            return fib_of(idx - 1) + fib_of(idx - 2);
        }
};

int main()
{
    Fibber x;

    for(int i = 1; i <= 100; i++)
    {
        std::cout << x.fib_of(i) << std::endl;
    }
}

Now, if we take that same program but add memoization:

#include <iostream>
#include <map>

class Fibber
{
    private:
        std::map<unsigned int, double> _fibs;

    public:
        double fib_of(unsigned int idx)
        {
            if(idx <= 2)
            {
                return 1;
            }
            
            double ret = 0;
            std::map<unsigned int, double>::iterator loc_iter = _fibs.find(idx);
            if(loc_iter != _fibs.end())
            {
                ret = loc_iter->second;
            }
            else
            {
                double calculated = fib_of(idx - 1) + fib_of(idx - 2);
                _fibs.insert(std::pair<unsigned int, double>(idx, calculated));
                ret = calculated;
            }

            return ret;
        }
};

int main()
{
    Fibber x;

    for(int i = 1; i <= 100; i++)
    {
        std::cout << x.fib_of(i) << std::endl;
    }
}

The difference in performance between the two is night-and-day.

The non-memoized variety will slow to an unresponsive crawl in very short order, because it has to calculate all the values leading up to the current value, repeatedly for each value; it forgets all the interim values on the way.

The memoized version remembers the interim values, and therefor only calculates them once, storing each in the cache.