Website may be up and down over next few months. I'm currently doing a complete overhaul of everything. Going back to simple individual .htm pages, new overall site theme, sanitizing and cleaning up html of all pages and blog posts, attempting to implement a new tooling and publishing system etc etc.

Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only

/// <summary>
/// Gets the depth of the three dimensional sequence.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array whose value is to be retrieves.</param>
/// <param name="width">The width of the three dimensional sequence.</param>
/// <param name="height">The height of the three dimensional sequence.</param>
/// <returns>Returns the depth of the three dimensional sequence.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// width or height is less then 1.
/// </exception>
public static int Get3DDepth<T>(this T[] array, int width, int height)
{
    if (width < 1)
    {
        throw new ArgumentOutOfRangeException("width");
    }

    if (height < 1)
    {
        throw new ArgumentOutOfRangeException("height");
    }

    return array.Length / (width * height);
}

Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only

/// <summary>
/// Inserts a source array into the three dimensional sequence.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array whose value is to be retrieves.</param>
/// <param name="width">The width of the three dimensional sequence.</param>
/// <param name="height">The height of the three dimensional sequence.</param>
/// <param name="destinationArray">The destination array.</param>
/// <param name="depth">The depth of the three dimensional sequence where insertion takes place.</param>
/// <param name="sourceArray">The source array to be inserted.</param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException">
/// width or height is less then 1. Or depth is less then 0.
/// </exception>
/// <exception cref="ArgumentException">'sourceArray' must not be larger then '(width * height)'.</exception>
/// <remarks>The length of the 'sourceArray' parameter cannot be larger then '(width * height)' otherwise the data it contains would overwrite any data
/// stored at a deeper depth.</remarks>
/// <returns>Returns the updated 'destinationArray'.</returns>
public static T[] Insert3D<T>(this T[] destinationArray, int width, int height, int depth, T[] sourceArray)
{
    if (width < 1)
    {
        throw new ArgumentOutOfRangeException("width");
    }

    if (height < 1)
    {
        throw new ArgumentOutOfRangeException("height");
    }

    if (depth < 0)
    {
        throw new ArgumentOutOfRangeException("depth");
    }

    if (sourceArray == null || sourceArray.Length == 0)
    {
        return destinationArray;
    }

    // ensure source array is no greater then width * height
    if (sourceArray.Length > (width * height))
    {
        throw new ArgumentException("'sourceArray' must not be larger then '(width * height)'", "sourceArray");
    }

    if (sourceArray.Length < (width * height))
    {
        Array.Resize(ref sourceArray, width * height);
    }

    destinationArray = destinationArray.Insert(depth * (width * height), sourceArray);

    // return the updated array
    return destinationArray;
}

Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only

/// <summary>
/// Sets the depth of the three dimensional sequence.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array whose value is to be retrieves.</param>
/// <param name="width">The width of the three dimensional sequence.</param>
/// <param name="height">The height of the three dimensional sequence.</param>
/// <param name="value">The new depth of the three dimensional sequence.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// width or height is less then 1.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">'value' must be greater then 0.</exception>
public static T[] Set3DDepth<T>(this T[] array, int width, int height, int value)
{
    if (width < 1)
    {
        throw new ArgumentOutOfRangeException("width");
    }

    if (height < 1)
    {
        throw new ArgumentOutOfRangeException("height");
    }

    if (value < 1)
    {
        throw new ArgumentOutOfRangeException("value");
    }

    // resize the array preserving contents
    Array.Resize(ref array, value * (width * height));

    return array;
}

Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only

/// <summary>
/// Gets the value in a single dimensional array that represents a three dimensional sequence.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array whose value is to be retrieves.</param>
/// <param name="width">The width of the three dimensional sequence.</param>
/// <param name="height">The height of the three dimensional sequence.</param>
/// <param name="x">The x index (0 to width - 1).</param>
/// <param name="y">The y index (0 to height - 1).</param>
/// <param name="z">The z index (0 to depth - 1).</param>
/// <returns>Returns the value stored in the array.</returns>
/// <exception cref="ArgumentOutOfRangeException">
/// width or height is less then 1.
/// </exception>
/// <remarks>
/// <p>This method provides an alternative to working with three dimensional arrays "var value = new int[3,3,3];" by operating 
/// on a single dimensional array using a math formula to determine the index into the array.</p>
/// <p>Think of a multi-layered image. Each image layer consists of a grid of cells defined by width * height.</p>
/// <p>We can use the formula "layer * (width * height)" to get the starting index of the layer in the array. 
/// To get the index in the image we can use the formula "(y * width) + x". 
/// Combining these two formulas we can access any grid cell of any layer in the array like so "(layer * (width * height)) + ((y * width) + x)".</p>
/// <p>This method does not perform range checking and will throw index out of range exceptions if invalid arguments are specified.</p></remarks>
public static T Get3D<T>(this T[] array, int width, int height, int x, int y, int z)
{
    if (width < 1)
    {
        throw new ArgumentOutOfRangeException("width");
    }

    if (height < 1)
    {
        throw new ArgumentOutOfRangeException("height");
    }

    return array[(z * (width * height)) + ((y * width) + x)];
}

Full repo available at https://bitbucket.org/createdbyx/codefarts.utilities-extension-methods-only

/// <summary>
/// Sets the value in a single dimensional array that represents a three dimensional sequence.
/// </summary>
/// <typeparam name="T">The type of the array.</typeparam>
/// <param name="array">The array whose value is to be set.</param>
/// <param name="width">The width of the three dimensional sequence.</param>
/// <param name="height">The height of the three dimensional sequence.</param>
/// <param name="x">The x index (0 to width - 1).</param>
/// <param name="y">The y index (0 to height - 1).</param>
/// <param name="z">The z index (0 to depth - 1).</param>
/// <param name="value">The value to set.</param>
/// <exception cref="ArgumentOutOfRangeException">
/// width or height is less then 1.
/// </exception>
/// <remarks>
/// <p>This method provides an alternative to working with three dimensional arrays "var value = new int[3,3,3];" by operating
/// on a single dimensional array using a math formula to determine the index into the array.</p>
/// <p>Think of a multi-layered image. Each image layer consists of a grid of cells defined by width * height.</p>
/// <p>We can use the formula "layer * (width * height)" to get the starting index of the layer in the array.
/// To get the index in the image we can use the formula "(y * width) + x".
/// Combining these two formulas we can access any grid cell of any layer in the array like so "(layer * (width * height)) + ((y * width) + x)".</p>
/// <p>This method does not perform range checking and will throw index out of range exceptions if invalid arguments are specified.</p>
/// </remarks>
public static void Set3D<T>(this T[] array, int width, int height, int x, int y, int z, T value)
{
    if (width < 1)
    {
        throw new ArgumentOutOfRangeException("width");
    }

    if (height < 1)
    {
        throw new ArgumentOutOfRangeException("height");
    }

    array[(z * (width * height)) + ((y * width) + x)] = value;
}

Takes in an array of floats representing pixels ordered left to right top to bottom. Width & height arguments specify the image dimensions.

        /// <summary>
        /// Smoothens out the image.
        /// </summary>
        /// <param name="image">The source image.</param>
        /// <exception cref="ArgumentNullException"><paramref name="getPixel"/> or <paramref name="setPixel"/> is <see langword="null" />.</exception>
        public static void Smoothen(this float[] image, int width, int height, Func<int, int, float> getPixel, Action<int, int, float> setPixel, float smoothinValue = 9f)
        {
            if (getPixel == null)
            {
                throw new ArgumentNullException("getPixel");
            }

            if (setPixel == null)
            {
                throw new ArgumentNullException("setPixel");
            }

            for (var x = 1; x < width - 1; ++x)
            {
                for (var y = 1; y < height - 1; ++y)
                {
                    var total = 0f;
                    for (var u = -1; u <= 1; u++)
                    {
                        for (var v = -1; v <= 1; v++)
                        {
                            total += getPixel(x + u, y + v);
                        }
                    }

                    setPixel(x, y, total / smoothinValue);
                }
            }
        }

The fallowing code snip is designed to take in a flat list of file paths (or similar data) and produce a hierarchy of tree nodes representing those file paths.

        /// <summary>
        /// Constructs a nested hierarchy of types from a flat list of source types.
        /// </summary>
        /// <typeparam name="TSource">The source type of the flat list that is to be converted.</typeparam>
        /// <typeparam name="TReturn">The type that will be returned.</typeparam>
        /// <typeparam name="TPart">The type of the art type.</typeparam>
        /// <param name="sourceItems">The source items to be converted.</param>
        /// <param name="getParts">A callback function that returns a array of <see cref="TPart"/>.</param>
        /// <param name="comparePart">The compare part callback.</param>
        /// <param name="getChildren">The get children callback.</param>
        /// <param name="addChild">The add child callback.</param>
        /// <param name="createItem">The create item callback.</param>
        /// <returns>Returns an collection of <see cref="TReturn"/> representing the hierarchy.</returns>
        /// <exception cref="Exception">A delegate callback throws an exception. </exception>
        private static IEnumerable<TReturn> ToHierarchy<TSource, TReturn, TPart>(
          IEnumerable<TSource> sourceItems,
        Func<TSource, TPart[]> getParts,
        Func<TReturn, TPart, bool> comparePart,
        Func<TReturn, IEnumerable<TReturn>> getChildren,
        Action<IEnumerable<TReturn>, TReturn> addChild,
        Func<TPart[], int, TSource, TReturn> createItem)
        {
            var treeModels = new List<TReturn>();
            foreach (var keyName in sourceItems)
            {
                IEnumerable<TReturn> items = treeModels;
                var parts = getParts(keyName);
                for (var partIndex = 0; partIndex < parts.Length; partIndex++)
                {
                    var node = items.FirstOrDefault(x => comparePart(x, parts[partIndex]));
                    if (node != null)
                    {
                        items = getChildren(node);
                        continue;
                    }

                    var model = createItem(parts, partIndex, keyName);
                    addChild(items, model);
                    items = getChildren(model);
                }
            }

            return treeModels;
        }

An example of how one could use the ToHierarchy method would be like this …

        var separator = new[] { Path.AltDirectorySeparatorChar.ToString(CultureInfo.InvariantCulture) };
        // paths varible could be something from Directory.GetDirectories method for example.
        var nodes = ToHierarchy<string, TreeViewNode, string>(
            paths.OrderBy(x => x),
            x => x.Split(separator, StringSplitOptions.RemoveEmptyEntries),
            (r, p) => string.CompareOrdinal(r.Name, p) == 0,
            r => r.Nodes,
            (r, c) => ((List<TreeViewNode>)r).Add(c),
            this.CreateTreeNode);

        private TreeViewNode CreateTreeNode(string[] parts, int index, string source)
        {
            var node = new TreeViewNode() { Name = parts[index] };
            node.Value = string.Join(Path.DirectorySeparatorChar.ToString(CultureInfo.InvariantCulture), parts, 0, index + 1);
            if (index == parts.Length - 1)
            {
                node.Name = Path.GetFileName(source);
            }

            node.IsFile = File.Exists(node.Value);
            return node;
        }

Where paths is a array of file paths from say Directory.GetFiles.


Source: http://stackoverflow.com/questions/616718/how-do-i-get-common-file-type-icons-in-c

    public static class FileIcon
    {
        [DllImport("shell32.dll")]
        private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);

        [StructLayout(LayoutKind.Sequential)]
        private struct SHFILEINFO
        {
            public IntPtr hIcon;
            public IntPtr iIcon;
            public uint dwAttributes;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
            public string szDisplayName;

            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)]
            public string szTypeName;
        };

        private const uint SHGFI_ICON = 0x100;
        private const uint SHGFI_LARGEICON = 0x0; // 'Large icon
        private const uint SHGFI_SMALLICON = 0x1; // 'Small icon

        public static System.Drawing.Icon GetLargeIcon(string file)
        {
            var shinfo = new SHFILEINFO();
            var hImgLarge = SHGetFileInfo(file, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), FileIcon.SHGFI_ICON | FileIcon.SHGFI_LARGEICON);
            return System.Drawing.Icon.FromHandle(shinfo.hIcon);
        }

        public static System.Drawing.Icon GetSmallIcon(string file)
        {
            var shinfo = new SHFILEINFO();
            var hImgLarge = SHGetFileInfo(file, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), FileIcon.SHGFI_ICON | FileIcon.SHGFI_SMALLICON);
            return System.Drawing.Icon.FromHandle(shinfo.hIcon);
        }
    } 

// <copyright>
//   Copyright (c) 2012 Codefarts
//   All rights reserved.
//   contact@codefarts.com
//   http://www.codefarts.com
// </copyright>

namespace Codefarts.ObjectPooling
{
    using System;

    /// <summary>
    /// Provides a generic object pooling manager.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class ObjectPoolManager<T> where T : class
    {
        /// <summary>
        /// Holds a reference to a singleton instance.
        /// </summary>
        private static ObjectPoolManager<T> instance;

        /// <summary>
        /// Used to track the number of items that have been pushed to the pool.
        /// </summary>
        private int count;

        /// <summary>
        /// Holds the pooled item references.
        /// </summary>
        private T[] cachedItems = new T[10000];


        /// <summary>
        /// Gets or sets the creation callback.
        /// </summary>
        public Func<T> CreationCallback { get; set; }

        /// <summary>
        /// Gets the number of items in the pool.
        /// </summary>
        public int Count
        {
            get
            {
                return this.count;
            }
        }

        /// <summary>
        /// Pops a item from the pool.
        /// </summary>
        /// <returns>A pooled object reference.</returns>
        /// <exception cref="System.NullReferenceException">'CreationCallback' property must be set if you try to pop a item and there are no items available.</exception>
        public T Pop()
        {
            // lock here to prevent treading conflicts with array manipulation
            lock (this.cachedItems)
            {
                // check if there are any pooled objects
                if (this.count < 1)
                {
                    // check if creation callback is null
                    if (this.CreationCallback == null)
                    {
                        throw new NullReferenceException("'CreationCallback' property must be set if you try to pop a item and there are no items available.");
                    }

                    // there are no available objects so create a new one.
                    return this.CreationCallback();
                }

                // reduce the count
                this.count--;

                // retrieve the item and return it
                return this.cachedItems[this.count];
            }
        }

        /// <summary>
        /// Pushes the specified value.
        /// </summary>
        /// <param name="value">The value to push into the pool.</param>
        public void Push(T value)
        {
            // lock here to prevent treading conflicts with array manipulation
            lock (this.cachedItems)
            {
                // update the count
                this.count++;

                // if we need more room for storage increase the size of the cache array
                if (this.count > this.cachedItems.Length)
                {
                    Array.Resize(ref this.cachedItems, this.cachedItems.Length * 2);
                }

                // store the value 
                this.cachedItems[this.count - 1] = value;
            }
        }

        /// <summary>
        /// Gets the singleton instance of the class.
        /// </summary>
        public static ObjectPoolManager<T> Instance
        {
            get
            {
                return instance ?? (instance = new ObjectPoolManager<T>());
            }
        }
    }
}

And some unit tests to go along with it.

// <copyright>
//   Copyright (c) 2012 Codefarts
//   All rights reserved.
//   contact@codefarts.com
//   http://www.codefarts.com
// </copyright>

namespace Codefarts.Tests.ObjectPooling
{
    using System;

    using Codefarts.ObjectPooling;

    using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;

    [TestClass]
    public class ObjectPoolingManagerTests
    {
        ObjectPoolManager<TestObject> manager;

        [TestInitialize]
        public void Setup()
        {
            this.manager = new ObjectPoolManager<TestObject>();
        }

        [TestCleanup]
        public void Cleanup()
        {
            this.manager = null;
        }

        public class TestObject
        {
            public string stringValue;
            public int intValue;
        }

        [TestMethod]
        public void Pop_With_Empty_Pool_NoCallback()
        {
            try
            {
                var item = this.manager.Pop();
                Assert.IsNotNull(item);
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is NullReferenceException);
            }
        }

        [TestMethod]
        public void Pop_With_Empty_Pool_WithCallback()
        {
            try
            {
                this.manager.CreationCallback = this.Callback;
                var item = this.manager.Pop();
                Assert.IsNotNull(item);
                Assert.AreEqual(0, item.intValue);
                Assert.AreEqual(null, item.stringValue);
            }
            catch (Exception ex)
            {
                Assert.IsTrue(ex is NullReferenceException);
            }
        }

        private TestObject Callback()
        {
            return new TestObject();
        }

        [TestMethod]
        public void Push_Object()
        {
            try
            {
                Assert.AreEqual(0, this.manager.Count);
                this.manager.Push(new TestObject());
                Assert.AreEqual(1, this.manager.Count);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.ToString());
            }
        }

        [TestMethod]
        public void Push_Pop_Objects()
        {
            try
            {
                Assert.AreEqual(0, this.manager.Count);
                for (var i = 0; i < 3; i++)
                {
                    this.manager.Push(new TestObject() { stringValue = "Item" + i, intValue = i });
                }

                Assert.AreEqual(3, this.manager.Count);

                for (var i = 3 - 1; i >= 0; i--)
                {
                    var item = this.manager.Pop();
                    Assert.AreEqual(i, item.intValue);
                    Assert.AreEqual("Item" + i, item.stringValue);
                }

                Assert.AreEqual(0, this.manager.Count);
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.ToString());
            }
        }
    }
}

Source (adapted for GenericImage) -> http://stackoverflow.com/a/11176961/341706

/// <summary>
        /// Rotates the image.
        /// </summary>
        /// <param name="image">
        /// The source image to rotate.
        /// </param>
        /// <param name="angle">
        /// The angle in degrees to rotate the image.
        /// </param>
        /// <param name="centerX">The x position of the rotation axis.</param>
        /// <param name="centerY">The y position of the rotation axis.</param>
        /// <returns>
        /// Returns a new rotated image.
        /// </returns>
        public static GenericImage<T> Rotate<T>(this GenericImage<T> image, int centerX, int centerY, float angle)
        {
            // source (adapted for GenericImage) -> http://stackoverflow.com/a/11176961/341706
            var radians = (Math.PI / 180) * angle;
            var cos = Math.Cos(radians);
            var sin = Math.Sin(radians);
            var newImage = new GenericImage<T>(image.Width, image.Height);

            for (var x = 0; x < image.Width; x++)
                for (var y = 0; y < image.Height; y++)
                {
                    var m = x - centerX;
                    var n = y - centerY;
                    var j = ((int)(m * cos + n * sin)) + centerX;
                    var k = ((int)(n * cos - m * sin)) + centerY;
                    if (j >= 0 && j < image.Width && k >= 0 && k < image.Height)
                    {
                        newImage[x, y] = image[j, k];
                    }
                }

            return newImage;
        }

Created by: X

Just another personal website in this crazy online world

Name of author Dean Lunz (aka Created by: X)
Computer programming nerd, and tech geek.
About Me -- Resume