Archive for the 'C#' Category

How to serve the same data in Json, Xml or Html with Asp.Net MVC

A revised version can be found here

About four weeks ago I went to a small event for developers where one of the speakers (christian dalager) compared Ruby on Rails to Asp.Net Mvc. One of the things that really caught my attention in Ruby on Rails was the ability to have an Action serve content in various formats like Json, Xml or Html just by changing the file extension of the requested resource.

I thought it would be cool if you could do something similar in Asp.net MVC and found it to be quite easy, however if you want to serve your content in Xml, you need to download MvcContrib.

To do this, we need to create a new controller that we can inherit from.

The Controller

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/// <summary>
/// A base controller that will enable you to serve your data in either Json, Xml, Html
/// </summary>
public abstract class FormatController : Controller
{
	/// <summary>
	/// The Key to extract the format from Route Data
	/// </summary>
	private const string FORMAT_KEY = "Format";
 
	/// <summary>
	/// The type of files we can server the requested content in
	/// </summary>
	public enum FileFormat { Html, Json, Xml }
 
	protected FormatController()
	{
		// Our Default format
		RequestedFormat = FileFormat.Html;
	}
 
	/// <summary>
	/// The format that has been requested
	/// </summary>
	protected FileFormat RequestedFormat { get; private set; }
 
	/// <summary>
	/// Occurs before an action is executed
	/// </summary>
	/// <param name="filterContext"></param>
	protected override void OnActionExecuting(ActionExecutingContext filterContext)
	{
		base.OnActionExecuting(filterContext);
 
		var routeValues = filterContext.RouteData.Values;
		if (routeValues.ContainsKey(FORMAT_KEY))
		{
			var requestedFormat = routeValues[FORMAT_KEY].ToString();
			if (IsValidFormat(requestedFormat))
			{
				RequestedFormat = (FileFormat)Enum.Parse(typeof(FileFormat), requestedFormat, true);
			}
		}
	}
 
	/// <summary>
	/// Verifies that the requested format is one that can be servered
	/// </summary>
	/// <param name="requestedFormat"></param>
	/// <returns></returns>
	private bool IsValidFormat(string requestedFormat)
	{
		return Enum.GetNames(typeof(FileFormat)).Any(format => format.ToLower() == requestedFormat.ToLower());
	}
 
	/// <summary>
	/// Returns the content in the requested format
	/// </summary>
	/// <param name="viewModel">Viewmodel</param>
	/// <returns>ActionResult</returns>
	protected ActionResult FormatView(object viewModel)
	{
		switch (RequestedFormat)
		{
			case FileFormat.Html:
				return View(viewModel);
			case FileFormat.Json:
				return Json(viewModel);
			case FileFormat.Xml:
				return new XmlResult(viewModel);
			default:
				throw new FormatException(string.Concat("Cannot server the content in the request format: ", RequestedFormat));
		}
	}
}

Setting it up

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Pizza
{
	public int Number { get; set; }
	public string Name { get; set; }
	public string Price { get; set; }
}
 
public class HomeController : FormatController
{
	public ActionResult Index()
	{
		var pizzas = new[]
			{
				new Pizza {Number = 1, Name = "Pizza 1", Price = "$10"},
				new Pizza {Number = 2, Name = "Pizza 2", Price = "$13"},
				new Pizza {Number = 3, Name = "Pizza 3", Price = "$20"}
			};
 
		return FormatView(pizzas);
	}
}
1
2
3
4
5
6
// Add this to Global.asax
routes.MapRoute(
	"Format",
	"{controller}/{action}.{format}/{id}",
	new {id = ""}
);

Fire up your application and then type something like “home/index.xml” or “home/index.json” in the browser.

Finale word

Imaging that on your website you have different categories that contain products, by applying this technique you will be able to create a REST like webservice for your users in no time, everyone will be able to integrate your website into their own.

Sharing data has never been easier, this is so awesome.

I have submittet this piece of code (and some other stuff) to MvcContrib, I hope that it makes into the project.

Further reading
A revised version can be found here
Controllers and Action Methods in MVC Applications

JSON (JavaScript Object Notation)

The Observer Pattern in C#

There are a few ways to implement this pattern and I will show you two different ways to do it, but first things first.

The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. - Head First, Design Patterns

When you are working with this pattern you usually have something called a Subject (sometimes referred to as Observerable) and an Observer. The Subject is an object that messages the Observers when its state is changed, just like it says in the above definition.

To illustrate how the pattern works you should think of a newspaper subscription, there you (the observer) subscribe to a newspaper (the subject) which you will receive when ever they send out a new issue.

In the first example we will look at how this pattern can be applied with a few interfaces and in the second example we will use a delegate and an event.

When this pattern is implemented in the right way you will have a loosely coupled design, which of course is something we want.

Example 1 – Using interfaces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
public interface ISubject
{
	void RegisterObserver(IObserver o);
 
	void RemoveObserver(IObserver o);
 
	void NotifyObservers();
}
 
public interface IObserver
{
	void Update(string story);
}
 
public class NewsPublisher : ISubject
{
	private List<IObserver> observers = new List<IObserver>();
 
	private List<string> archive = new List<string>();
 
	public void RegisterObserver(IObserver o)
	{
		observers.Add(o);
	}
 
	public void RemoveObserver(IObserver o)
	{
		observers.Remove(o);
	}
 
	public void NotifyObservers()
	{
		foreach(IObserver o in observers)
		{
			o.Update(archive[archive.Count - 1]);
		}
	}
 
	public void PublishBreakingNews(string story)
	{
		archive.Add(story);
		ArchiveChanged();
	}
 
	private void ArchiveChanged()
	{
		NotifyObservers();
	}
}
 
public class NewsSubscriber : IObserver
{
	public void Update(string story)
	{
        Console.WriteLine("--------------------- Breaking News ---------------------");
        Console.Write(story);
        Console.WriteLine();
	}
}
 
class Program
{
	static void Main(string[] args)
	{
		NewsSubscriber me = new NewsSubscriber();
 
		NewsPublisher publisher = new NewsPublisher();
 
		publisher.RegisterObserver(me);
 
		publisher.PublishBreakingNews("hello world");
	}
}

Example 2 – Using delegates and events

This example look a lot like the Event Pattern, but there are a few conventions that differs like the name convention but also how the signature of the method looks like for the delegate, but since we aren’t using that pattern let’s move on.

I have added a few comments here and there to show the similarities between the previous example and this one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/// <summary>
/// Observer
/// </summary>
public class NewsSubscriber
{
	public void Update(string story)
	{
		Console.WriteLine("--------------------- Breaking News ---------------------");
		Console.Write(story);
		Console.WriteLine();
	}
}
 
/// <summary>
/// Subject
/// </summary>
public class NewsPublisher
{
	private readonly List<string> archive = new List<string>();
 
	public delegate void NotifyObserversHandler(string story);
 
	public event NotifyObserversHandler ArchiveChanged;
 
	public void PublishBreakingNews(string story)
	{
		archive.Add(story);
 
		// Notify observers
		ArchiveChanged(archive[archive.Count - 1]);
	}
}
 
class Program
{
	static void Main(string[] args)
	{
		NewsSubscriber me = new NewsSubscriber();
		NewsPublisher publisher = new NewsPublisher();
 
		//add the delegate to the event (register observer)
		publisher.ArchiveChanged += me.Update;
 
		publisher.PublishBreakingNews("Hello world");
	}
}

Finale word

As you can see the two examples work pretty much the same way, so it is really up to you to choose which one you prefer.

Further reading

Head First, Design Patterns

Events and Delegates

Exploring the Observer Design Pattern

The Common Service Locator from Microsoft Patterns & Practices

The Common Service Locator (CSL) is a helpful library and at first sight it might look like some new cool thing that you need, but it really depends on what you are trying to build.

Do I need it?

Typically, the answer to this question is no. Once you’ve decided on a container that suits your project, there’s not a whole lot of benefit from writing your whole application in a way that can switch containers. – The CSL Wiki

The library will just provide you with an extra layer of abstraction and is only meant for people who are building frameworks where there is a need for allowing people to specify what kind of DI (dependency injection) container they want to use, so that they aren’t tied down to using a specific implementation made by the authors.

Using the library and creating the adaptor

There are a few ways to have the adapter implement the interface. You can either use the IServiceLocator interface or you can use ServiceLocatorImplBase, which is used as a convenience for those who wants to implement the IServiceLocator interface.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class MyServiceLocatorAdapter : ServiceLocatorImplBase
{
    private IMyContainer container;
 
    public MyServiceLocatorAdapter(IMyContainer container)
    {
        this.container = container;
    }
 
    protected override object DoGetInstance(Type serviceType, string key)
    {
        return container.Resolve(serviceType, key);
    }
 
    protected override IEnumerable<object> DoGetAllInstances(Type serviceType)
    {
        return container.ResolveAll(serviceType);
    }
}

You only need to implement the two protected methods and then you are good to go. Now you are ready create your own adapter, but you can also find a few that has already been written.

Setting it up

I have changed the above example a bit, so that it will take a UnityContainer.

1
2
3
4
5
6
7
8
IUnityContainer container = new UnityContainer();
container.RegisterType<ISomeRepository, SomeRepository>();
 
MyServiceLocatorAdapter locator = new MyServiceLocatorAdapter(container);
 
ServiceLocator.SetLocatorProvider(() => locator);
 
ISomeRepository repository = ServiceLocator.Current.GetInstance<ISomeRepository>();;

Finale word

There are of course already a few online, so you might as well take advantage of them instead of starting from scratch.

If you are going to use this, make sure you check out this blog first because there are a few pitfalls that you need to be aware of.

Further reading

How to setup the Unity Container

Common Service Locator Wiki

« Previous PageNext Page »