Category Archives: Common

Numeric converter using different bases

Inspired by a short conversation with jsilence I was looking for a NewBase60 converter written in Java and C#.

NewBase60 is a format suitable for building parts of URLs, e.g. for URL shorteners. Instead of just using numbers for the short links it uses letters as well, while internally still using numeric values. (There are different strategies to increase a numeric value: just increase the number, increase it using hexadecmial notation, or using an extended set of characters like NewBase60 does it.)

Sadly, the NewBase60 posting didn’t list a C# implementation, and the link to the Java implementation was broken.

So I decided to write my own version. And while NewBase60 with its given 60 characters is just a special case for such numeric conversions, my Base-N implementation not only includes NewBase60 but also a binary, octal and a hexadecimal converter, a flexible base implementation for user-defined bases/alphabets and a “max. base 36” implementation.

The Base-N code is up on my github page, so feel free to download, use and/or fork it.

If you encounter any bugs or just want to provide any other (positive?) feedback, feel free to leave a comment below.

C# Extension Methods, Part 3

While I’ll probably (have to) focus on Java for the next month, I just came up with the idea of just another extension method class. It is acually not very helpful but it again shows how powerful extension methods can be.

This is how it can be used:

StringBuilder buffer = new StringBuilder();
foreach (int i in 10.To(15))
{
    buffer.AppendLine("" + i);
}

I know that this piece of code does not look very helpful, because the same can easily be done using a simple for loop, but there might be some cases – especially when using LINQ – when it is quite useful to have an iterable range of int values.

The code is up on my github C# extension method project. Feel free to use or fork it.

Timelapse, experimental (April 2012)

Last weekend I tried a timelapse software on my mobile phone, and here’s the result:

I think I’ll do more of these…

Moving the extension methods project to github

Some time ago I started to write a class with some C# extension methods, adding more methods over time. I first uploaded the file to the webspace of my blog, but I think this is getting too complicated to mantain, which makes it harder than required to post new versions.

So I’ve put the code on github: https://github.com/jcoder/jCsharpExtensions

Feel free to stay updated there, fork it or just download it. If you have any comments or suggestions, please leave them in the comments below.

C# Extension Methods, Part 2

I’ve just made another tiny addition to my extension method class / project, adding a small, but maybe useful method:

/// <summary>
/// Repeats this IEnumerable a given number of times
/// </summary>
/// <param name="enumerable">this IEnumerable</param>
/// <param name="times">number of times to repeat this IEnumerable</param>
/// <returns>IEnumerable</returns>
public static IEnumerable<T> Repeated<T>(this IEnumerable<T> enumerable, int times)
{
    if (times < 1)
    {
        yield break;
    }
    for (int i = 0; i < times; i++)
    {
        foreach (T oneObject in enumerable)
        {
            yield return oneObject;
        }
    }
}

This is how to use it to consume an IEnumerable<T> multiple times:

var range = Enumerable.Range(1, 5);
foreach (var i in range.Repeated(5))
{
    // doing something with i, which will be the sequence
    // from 1 to 5, repeated 5 times
}

It’s not a big deal, but maybe it’s helpful anyway. Btw, the source code is updated, too.

A sneak peek into Apache James

I’ve been playing around with Apache James, a complete email server written in Java, in the last few months and I’d like to share some of my thoughts about it. (I’ll focus on version 2.3.2 as the 3.0 version is still in beta.)

In short
Apache James is a flexible, highly configurable and extendable email server (SMTP, POP3, IMAP4 [since James 3.0]). It can store emails and users either in the file system or in a database (e.g. MySQL, PostgreSQL, and others) and handles emails for multiple domains via mappings.

Some insights
There is a comprehensive documentation at the James website including a wiki, so I will not go too much into detail here. Some of the server’s main concepts are storage, processor, matcher and mailet.

Storage
Both emails and users (and other configuration data) is persisted in the storage. James comes with a filesystem-based and a JDBC-based storage implementation, but other types of storage are possible too (e.g. LDAP, JPA and others, some of them will be provided with version 3.0).

Processor
When an incoming email is processed by the server it is injected into a so-called processor, which is a kind of queue consisting of actions to be performed on the email. Those actions are performed by the mailets.

Mailets
A mailet is similar to a servlet in a web container (like Tomcat), but it handles an incoming email instead of an HTTP request. James comes with many ready-to-go mailets, but it is very easy to implement own mailets to perform special tasks.

Matcher
A matcher decides if a a mailet will be executed for an incoming email. It checks if a condition is met and tells the email engine to execute the associated mailet.

Making it work all together
Sounds all a little bit confusing? Actually it isn’t. This is how everything works together:

  • The email engine receives an incoming email, wrapping it internally with an container (which provides some helpful functions)
  • The email engine forwards the the wrapped email to the processor named “root”
  • The “root” processor consists of a sequence of mailets, each having a matcher associated.
  • The mailet’s matcher is executed, returning whether or not the mailet should be executed.
  • The matcher is then executed (or maybe not). It will “do something” with the email, e.g. a virus check, some validation, changing data, forwarding or rejecting or discarding the email, putting it into another processor, or doing some other action.
  • If the email was not discarded, then the next mailet is processed, then the next, and so on.

Actually, there is a lot more going on internally, and in many points I oversimplified things here, but I just to give you a first impression about how James works.

Why is this so great (or useful)?
For me the most interesting point is that you can completely configure and extend the way how an incoming  email is processed. You can directly interact with an incoming email: you can convert its content or forward it to a custom script or handle it any other way that you can imagine.

One example? Sure!
The following mailet adds support for an address mapping to receive emails with multiple address suffixes into one account: an email address like jcoder+projectone@example.com
will become jcoder@example.com (and will be delivered to the account “jcoder” then.)

package me.jcoder.blog.examples.james.mailet;

import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import javax.mail.MessagingException;
import org.apache.mailet.GenericMailet;
import org.apache.mailet.Mail;
import org.apache.mailet.MailAddress;

/**
 * Mailet to support the "plus sign alias" syntax in addresses, so that
 * name+something@domain becomes name@domain
 * @author jCoder
 */
public class PlusAliasSupport extends GenericMailet {
    private static final String MAILET_NAME = "PlusAliasSupport";

    @Override
    public void service(Mail mail) throws MessagingException {
        if (mail == null) {
            return;
        }
        try {
            Collection recipients = mail.getRecipients();
            Collection recipientsToRemove = new LinkedList();
            Collection recipientsToAdd = new LinkedList();
            for (Iterator itr = recipients.iterator(); itr.hasNext(); ) {
                MailAddress address = (MailAddress)itr.next();
                if (address == null) {
                    continue;
                }
                String localPartStr = address.getUser();
                int plusIndex = -1;
                if ((localPartStr != null) && ((plusIndex = localPartStr.indexOf('+')) > -1)) {
                    String newLocalPart = localPartStr.substring(0, plusIndex);
                    MailAddress replaceAddress = new MailAddress(newLocalPart, address.getHost());
                    recipientsToRemove.add(address);
                    recipientsToAdd.add(replaceAddress);
                }
            }
            recipients.removeAll(recipientsToRemove);
            recipients.addAll(recipientsToAdd);
        } catch (Exception ex) {
        }
    }

    @Override
    public String getMailetName() {
        return MAILET_NAME;
    }
}

It’s pretty helpful to get the source code of James to take a lokk at how the provided mailets and matchers are implemented.

Some notes and tipps
When writing matchers and mailets or running James as your (test) email server, there might be some pitfalls, so I’ll share some of the points that I came across.

  • When writing matchers and mailets you might want to download the Mailet SDK from the James website. This is generally a good idea, but make sure that you get the right version! James 2.3.2 normally uses the Mailet 2.3 API and the website provides the 2.4 API, so things will not work. If in doubt, add the mailet API-related JARs from a James installation.
  • When placing the JAR into the ${JAMES_DIR}/apps/james/SAR_INF/lib folder, don’t forget to add your mailet/matcher package name to the mailetpackagesmatcherpackages section of the config.xml file so it can be found by the server.
  • If you are going to use the JDBC-based storage, you need to put the JDBC driver for your database in a directory where the server can find it. It might not be best-practise, but I suggest to put the JDBC driver JAR into ${JAMES_DIR}/lib where it is accessable by the main server.
  • The same goes for using TLS/SSL. If you want to provide secure POP3 access, then you not only need a certificate (which is a whole other story to maybe being covered in an other posting), but you might run into some SSL-socket-related errors. One solution is to copy the sunjce_provider.jar from your Java runtime into ${JAMES_DIR}/lib as well.
I hope that this posting gives you a first impression about the flexibility of the email server James. If you have any questions or ideas, feel free to leave a comment.

Continuous project: C# Extension Methods

There are a lot of cool features in the current C# version (and I’m sure that I will cover most of them in future postings), but one of the features I like most are Extension Methods.

If you’ve never heard about Extension Methods, let me cite the MSDN documentation on Extension Methods:

Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.

Extension Methods are a very powerful feature when it comes to writing easy-to-understand code. So, over the course of the weeks and months I’ll post code fragments with (mostly) helpful Extension Methods, at least if they’re helpful for me. I will also upload the latest source code files to my blog.

Unless otherwise stated the code is provided as “Public Domain” which means that you can modify and use it in all your projects.

So, let’s get started with the first methods.

/// <summary>
/// Performs an action with each of the elements in this IEnumerable
/// </summary>
/// <param name="enumerable">this IEnumerable</param>
/// <param name="action">action to be performed on each element</param>
/// <returns>IEnumerable</returns>
public static IEnumerable<T> WithEach<T>(this IEnumerable<T> enumerable, Action<T> action) {
	if (action == null) {
		action = (obj) => {};
	}
	foreach (T oneObject in enumerable) {
		action(oneObject);
		yield return oneObject;
	}
}

/// <summary>
/// Concatinates all elements of this IEnumerable to a flat string, optionally quoting them
/// </summary>
/// <param name="enumerable">this IEnumerable</param>
/// <param name="glue">glue between the elements</param>
/// <param name="quoteStart">quote at start of each element</param>
/// <param name="quoteEnd">quote at end of each element</param>
/// <returns>flat string</returns>
public static string ToFlatString<T>(this IEnumerable<T> enumerable, string glue, string quoteStart, string quoteEnd) {
	if (glue == null) {
		glue = ",";
	}
	if (quoteStart == null) {
		quoteStart = "";
	}
	if (quoteEnd == null) {
		quoteEnd = "";
	}
	StringBuilder strBuilder = new StringBuilder();
	bool useGlue = false;
	foreach (T oneObject in enumerable) {
		if (useGlue == true) {
			strBuilder.Append(glue);
		} else {
			useGlue = true;
		}
		strBuilder.Append(quoteStart).Append(oneObject).Append(quoteEnd);
	}
	return strBuilder.ToString();
}

But wait, there’s more ;)

public static string ToFlatString<T>(this IEnumerable<T> enumerable, string glue)
public static string ToFlatString<T>(this IEnumerable<T> enumerable, string glue, Func<T, string> toStringFnc)

As don’t want this posting to be just code, I’ve only outlined the additional method signatures here, so feel free to download the complete file from http://blog.jcoder.me/files/csharp/IEnumerableExtensions.cs

If you have any questions or ideas for useful Extension Methods, please leave a comment below.