Earth in the universe

We are so small (click the images to see them in bigger size):

Published on Jul 4th, 2007 — Tags: ,
Comments (0)    digg it!    kick it   

Annotations: tagging .NET objects

Extension methods in C# 3.0 are a great thing! Alex Henderson (from New Zealand) has build a small library for C# 3.0 that allows to annotate (or tag) objects.

public void QueryStoreForClassAnnotationsWithCertainKey()
{
    ClassA target1 = new ClassA();
    ClassA target2 = new ClassA();
    ClassA target3 = new ClassA();

    // Tag some objects.
    target1.Annotate(Description => “class number 1″);
    target2.Annotate(Description => “class number 2″);
    target3.Annotate(Parsed => true);

    // Get the objects with the given key.
    var results = AnnotationStore.Classes
      .Where(a => a.HasKey(“Description”))
      .ToList();

    Assert.AreEqual(2, results.Count);
}

This library is a very interesting and creative way to use extension methods in C# 3.0. I wonder what other creative ideas are going to come up that are using extension methods.

Published on Jul 4th, 2007 — Tags: , , ,
Comments (0)    digg it!    kick it   

Clipboard history

Ever put something in the clipboard and accidentally replaced it by copying something else in the clipboard? If that’s true you need a program that monitors the clipboard and creates a history for you.

I have written such a program: it monitors the Windows clipboard and creates a history that contains the last 25 items that have been put into the clipboard. The project is found in the project section of my web site and has been recently added to softpedia (without my knowledge). :)

The ZIP file contains the binaries and full source code!

Published on Jul 3rd, 2007 — Tags:
Comments (0)    digg it!    kick it   

Sample: Encrypt and compress in .NET

Channel 9 is a source of inspiration with all the questions that are asked. Today in a second post somebody asked about a problem in his compression and encryption code. I looked at the code and thought why not to create an own utility class that compresses/decompresses and encrypts/decrypts a piece of data.

That’s what I got (the comments make the code very much self explaining):

public static class EncryptAndCompressUtility
{
    /// <summary>
    /// Encrypts and compresses the input. Returns the compressed and encrypted content and the key and iv vector used.
    /// </summary>
    /// <param name="input">The input array.</param>
    /// <param name="key">The key that has been used by the algorithm.</param>
    /// <param name="iv">The iv vector that has been used by the algorithm.</param>
    /// <returns></returns>
    public static byte[] EncryptAndCompress(byte[] input, out byte[] key, out byte[] iv)
    {
        if (input == null)
            throw new ArgumentNullException(“input”);

        // Compress the input array into the given memory stream.
        MemoryStream stream = new MemoryStream();
        using (GZipStream zip = new GZipStream(stream, CompressionMode.Compress, true))
        {
            // Write the input to the memory stream via the ZIP stream.
            zip.Write(input, 0, input.Length);
        }

        // Create the keys and initalize the rijndael.
        RijndaelManaged r = new RijndaelManaged();
        r.GenerateKey();
        r.GenerateIV();
        // Set the generated key and iv vector.
        key = r.Key;
        iv = r.IV;

        // Encrypt the compressed memory stream into the encrypted memory stream.
        MemoryStream encrypted = new MemoryStream();
        using (CryptoStream cryptor = new CryptoStream(encrypted, r.CreateEncryptor(), CryptoStreamMode.Write))
        {
            // Write the stream to the encrypted memory stream.
            cryptor.Write(stream.ToArray(), 0, (int)stream.Length);
            cryptor.FlushFinalBlock();
            // Return the result.
            return encrypted.ToArray();
        }
    }

    /// <summary>
    /// Decrypts and decompresses the input. Returns the decompressed and decrypted content.
    /// </summary>
    /// <param name="input">The input array.</param>
    /// <param name="key">The key used for decrypt.</param>
    /// <param name="iv">The iv vector used for decrypt.</param>
    /// <returns></returns>
    public static byte[] DecryptAndDecompress(byte[] input, byte[] key, byte[] iv)
    {
        if (input == null)
            throw new ArgumentNullException(“input”);
        if (key == null)
            throw new ArgumentNullException(“key”);
        if (iv == null)
            throw new ArgumentNullException(“iv”);

        // Initialize the rijndael
        RijndaelManaged r = new RijndaelManaged();
        // Create the array that holds the result.
        byte[] decrypted = new byte[input.Length];
        // Create the crypto stream that is used for decrypt. The first argument holds the input as memory stream.
        using (CryptoStream decryptor = new CryptoStream(new MemoryStream(input), r.CreateDecryptor(key, iv), CryptoStreamMode.Read))
        {
            // Read the encrypted values into the decrypted stream. Decrypts the content.
            decryptor.Read(decrypted, 0, decrypted.Length);
        }

        // Create the zip stream to decompress.
        using(GZipStream zip = new GZipStream(new MemoryStream(decrypted), CompressionMode.Decompress, false))
        {
            // Read all bytes in the zip stream and return them.
            return ReadAllBytes(zip);
        }
    }

    /// <summary>
    /// Reads all bytes in the given zip stream and returns them.
    /// </summary>
    /// <param name="zip">The zip stream that is processed.</param>
    /// <returns></returns>
    private static byte[] ReadAllBytes(GZipStream zip)
    {
        if (zip == null)
            throw new ArgumentNullException(“zip”);

        int buffersize = 100;
        byte[] buffer = new byte[buffersize];
        int offset = 0, read = 0, size = 0;
        do
        {
            // If the buffer doesn’t offer enough space left create a new array
            // with the double size. Copy the current buffer content to that array
            // and use that as new buffer.
            if (buffer.Length < size + buffersize)
            {
                byte[] tmp = new byte[buffer.Length * 2];
                Array.Copy(buffer, tmp, buffer.Length);
                buffer = tmp;
            }

            // Read the net chunk of data.
            read = zip.Read(buffer, offset, buffersize);

            // Increment offset and read size.
            offset += buffersize;
            size += read;
        } while (read == buffersize); // Terminate if we read less then the buffer size.

        // Copy only that amount of data to the result that has actually been read!
        byte[] result = new byte[size];
        Array.Copy(buffer, result, size);
        return result;
    }
}

It can be used like in the following example:

byte[] key = null;
byte[] iv = null;
byte[] input = File.ReadAllBytes(“C:\\Users\\Chris\\Documents\\UNI\\Untitled.bmp”);

byte[] result = EncryptAndCompressUtility.EncryptAndCompress(input, out key, out iv);
File.WriteAllBytes(“C:\\Users\\Chris\\Documents\\UNI\\foo compressed.bmp”, result);

byte[] result2 = EncryptAndCompressUtility.DecryptAndDecompress(File.ReadAllBytes(“C:\\Users\\Chris\\Documents\\UNI\\foo compressed.bmp”), key, iv);
File.WriteAllBytes(“C:\\Users\\Chris\\Documents\\UNI\\foo.bmp”, result2);

Published on Jul 2nd, 2007 — Tags: ,
Comments (5)    digg it!    kick it   

Get all files in a directory and sub directories by extension(s)

A post over at Channel 9 inspired me to create a simple class to do directory listing by extensions. The problem guy’s problem was that he could only use one extension when doing a file listing of a directory. My new class allows to search for multiple file extensions in one run:

public static class DirectoryListing
{
    /// <summary>
    /// Gets the files by the given extensions from the given path.
    /// </summary>
    public static string[] GetFilesByExtensions(string path, string extensions, SearchOption option)
    {
        List<string> result = new List<string>();
        InternalGetFiles(path, option, extensions.Split(‘;’), result);
        return result.ToArray();
    }

    private static void InternalGetFiles(string path, SearchOption option, string[] extensions, List<string> result)
    {
        // Get the files.
        string[] files = Directory.GetFiles(path);
        foreach (string file in files)
        {
            // Get the extension of the file.
            string ext = Path.GetExtension(file);
            // Validate the extension against the searched extensions.
            foreach (string p in extensions)
            {
                if (ext == p)
                {
                    result.Add(file);
                    break;
                }
            }
        }

        // Returns if only top directory is requested.
        if (option == SearchOption.TopDirectoryOnly)
            return;
        // Get all other directories.
        foreach (string directory in Directory.GetDirectories(path))
        {
            InternalGetFiles(directory, option, extensions, result);
        }
    }
}

I’m using a List<string> (as temporary container for the found files) in this example, because it makes it easy to add new results to it. A list is a smart array, which doubles the internal array’s size (and copies the current items to the new array) when the internal array is full.

Usage would look like this:

string[] files = DirectoryListing.GetFilesByExtensions(
    “C:\\Users\\Chris\\Documents\\, “.txt;.docx;.doc”,
    SearchOption.AllDirectories);

Published on Jul 2nd, 2007 — Tags: ,
Comments (1)    digg it!    kick it