Archive for the 'Asp.NET' Category

How to setup Dependency Injection with Microsoft Unity in Asp.net Mvc

Dependency Injection (DI) is a pretty great technique that will help you decouple a service from a client. The way it works, is that when a client is created a service will be applied in the instantiation of the client, so that it holds a reference to the service. You can of course inject multiple services, if you want to.

The description of DI might be a bit vague, because the term service seems to be used for anything these days. I hope the examples will shed some light on it.

Let’s see how things will look like without DI - This can of course be done a bit differently, but for the sake of the example we will just keep it like this.

1
2
3
4
5
6
7
8
9
public class HomeController : Controller
{
	public void Index()
	{
		ISomeRepository repo = new SomeRepository();
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

Let’s move on to an example where DI comes into play.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class HomeController : Controller
{
	private ISomeRepository repo;
 
	public HomeController(ISomeRepository someRepository)
	{
		repo = someRepository;
	}
 
	public void Index()
	{
		ViewData["content"] = repo.FindContent();
		return View();
	}
}

We need to do a little bit more than this. So let’s download Unity from Microsoft and include it in our project. Then we can create a new ControllerFactory.

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
public class UnityControllerFactory : DefaultControllerFactory
{
	private readonly IUnityContainer _container;
 
	public UnityControllerFactory(IUnityContainer container)
	{
		_container = container;
	}
 
	protected override IController GetControllerInstance(Type controllerType)
	{
		if (controllerType == null)
		{
			throw new HttpException(0x194, "No Controller Found");
		}
 
		if (!typeof(IController).IsAssignableFrom(controllerType))
		{
			throw new ArgumentException("TypeDoesNotSubclassControllerBase", 
				"controllerType");
		}
 
		return _container.Resolve(controllerType) as IController;
	}
}

So far, so good. We will now set it up in the Global.asax file. Of course, you will need to create some sort of service, if you want to test this. In my example I assume that I have a service called SomeRepository available to me, which implements the interface ISomeRepository.

1
2
3
4
5
6
7
8
protected void Application_Start()
{
	IUnityContainer container = new UnityContainer();
	container.RegisterType<ISomeRepository, SomeRepository>();
 
	UnityControllerFactory factory = new UnityControllerFactory(container);
	ControllerBuilder.Current.SetControllerFactory(factory);
}

That’s it! You have now injected your first service into a Controller.

The great thing about this is that you can now unit test your controllers with a mock implementation of a service, as long as it implements the interface.

If you have been using MonoRail, then you probably know about Windsor, so if you don’t like to use Unity, you can easily switch Unity out.

Ps. Using DI can be a good thing, but using it extensively can make things too complex, which is a bad thing.

How to prevent SQL Injection

Recently, I did a code review on web application that a colleague had developed, and to my horror I discovered that is was wide open to this sort of attack. I might be a bit naive, but I thought that every professional developer knew about this sort of attack – I guess not. Luckily for us (who use .net) this is something that can be prevented fairly easy and it should be.

What is SQL Injection

“SQL injection is a technique that exploits a security vulnerability occurring in the database layer of an application.” - Wikipedia.

Example

http://www.mysite.com/product.aspx?id=1000

1
2
string id = Request.QueryString("id");
string sql = "SELECT * FROM products WHERE id = '" + id + "'";

If you are doing something like this, then your database can be hacked. If SQL Injection is new to you, then you are probably thinking - How? It is really straight forward.

Example

http://www.mysite.com/product.aspx?id=1000`;DROP Database myDB

this will be executed against the database like so

1
SELECT * FROM products WHERE id = ‘`;DROP DATABASE myDB –

How to prevent this

Lets rewrite the above example so it will become safer.

Example

1
2
3
4
5
6
7
8
9
10
11
12
string id = Request.QueryString("id");
 
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
	string sql = "SELECT * FROM products WHERE id = @id"
	using (SqlCommand command = new SqlCommand(sql, connection))
	{
	    command.Parameters.Add("@id", SqlDbType.VarChar).Value = id; 
 
	    // Do something
	}
}

The great thing about this is that ADO.NET knows how to encode the ID value and thereby prevent someone from sneaking in some evil SQL expression.

Final word

The above example will help you a lot, if you are new to this subject but another thing you want to watch out for is someone trying to insert javascript into your database. There are a lot of websites who are infected with evil javascript because they don`t validate the input from the user, so validate the input, never trust the data.

Here is another great post about the subject.

ASP.NET Runtime Cheat Sheet: HttpRequest, HttpRuntime, AppDomain and friends

A very good article that contains a lot of usefull data

http://duartes.org/gustavo/articles/Asp.net-Runtime-Cheat-Sheet-HttpRequest-HttpRuntime.aspx

« Previous PageNext Page »