Of Code and Me

Somewhere to write down all the stuff I'm going to forget and then need

ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined. January 25, 2010

Filed under: Django,Error,Python — Rupert Bates @ 12:14 pm

If you get the following error when trying to use a Django package from the interactive prompt in Pydev:
“ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.”

You can solve it by setting the required environment variable in the __init__.py file of your app as follows:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings'
 

Ruby’s ‘times()’ function in C# January 24, 2010

Filed under: C#,Coding,Uncategorized — Rupert Bates @ 10:20 pm

I’ve seen a lot of people enthuse about Ruby’s times() function which allows you to write code like:

5.times { |i| puts i }

which prints out:
0
1
2
3
4
It is a really nice syntax and it struck me that you could use similar syntax in C# by defining the following extension method on int:

public static class IntExtensions
{
	public static void Times(this int i, Action<int> func)
	{
		for(int j = 0; j < i; j++)
		{
			func(j);
		}
	}
}

Which then lets you write:

5.Times(i => Console.Write(i));

with the same results

 

Create a UrlHelper from a library class in asp.net mvc January 7, 2010

Filed under: Uncategorized — Rupert Bates @ 11:13 am

If you need to get hold of a UrlHelper outside a controller, for instance to work out a url from an action in a library class, you can use the following function:

		public static UrlHelper GetUrlHelper()
		{
			var httpContext = new HttpContextWrapper(HttpContext.Current);
			return new UrlHelper( new RequestContext(httpContext, CurrentRoute(httpContext)));
		}
		public static RouteData CurrentRoute(HttpContextWrapper httpContext)
		{
			return RouteTable.Routes.GetRouteData(httpContext);
		}