Creating a Custom Authentication Backend using Django

Today I have posted a new tutorial on djangorocks.com ‘Creating a Custom Authentication Backend‘.

The example created allows you to login to your Django application using your IMAP mail server to check your username & password.  Perfect if you are creating a webmail client or address book – and more I’m sure.

The tutorial is not as long as I would have hoped, but its rather difficult to add to when it really is quite a simple thing to implement.  Hope it helps.

Threading / Background tasks in C# using BackgroundWorker

A simple way to use thread some slower tasks, with a callback method.

It uses the BackgroundWorker.  I found this to be the simplest way to achieve what I needed. The 2 tasks I used it for were image resize & sending E-mails – doing things over the web can be slow.

// Define a new BackgroundWorker
BackgroundWorker bw = new BackgroundWorker();

// This will be threaded
bw.DoWork += delegate(object sender, DoWorkEventArgs e)
{
    BackgroundWorkerConfig cfg = (BackgroundWorkerConfig) e.Argument;
    e.Result = cfg.myVariable.ToUpper();
};

// When the thread is complete, this runs
bw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
{
    BackgroundWorkerConfig cfg = (BackgroundWorkerConfig) e.Result;
    Console.WriteLine("Completed: " + cfg.myVariable);
};

// Start the process
bw.RunWorkerAsync(new BackgroundWorkerConfig("my string goes here"));

// A class used for sending configuration variables into the Worker
class BackgroundWorkerConfig
{
    public string myVariable;
    
    public BackgroundWorkerConfig(string myVariable) {
        this.myVariable = myVariable;
    }
}

If you don’t need to send variables in, or care about getting them out, you can remove everything related to the BackgroundWorkerConfig – ie Batch Resizing images from a pre-defined folder.

C# – Very Basic XML Parsing

In my app I have a VERY basic XML file with a list of countries & country codes. It looks like this;

<xml>
<item><code>ABW</code><country>Aruba</country></item>
<item><code>AFG</code><country>Afghanistan</country></item>
</xml>

Parsing this is very simple.
Using System.Xml;

XmlDocument xml = new XmlDocument();
xml.load("countries.xml");
XmlNodeList nodes = xml.SelectNodes("/xml/item");
foreach(XmlNode node in nodes) {
    Console.WriteLine(node["code"].InnerText + " = " + node["country"].InnerText);
}

Maybe you can use this as the basis for an RSS reader (although I’m sure there are better alternatives) .  I use it just to populate a drop-down box & convert from the country code to name.

Dansette