.Net MVC C# render nested HTML elements using a TagBuilder

The following HTMLHelper uses the TagBuilder class to render nested HTML elements.

public static class HtmlHelpers
    {
        public static MvcHtmlString RenderATag(this HtmlHelper htmlHelper, string uri, string cssClassName, string dataValue)
        {
            // Build A tag
            var aTagBuilder = new TagBuilder("a");

            aTagBuilder.MergeAttribute("href", uri);

            // Build I tag
            var iTagBuilder = new TagBuilder("i");

            // Add extension
            iTagBuilder.MergeAttribute("class", cssClassName);

            // Add the data attribute
            iTagBuilder.MergeAttribute("data-name", dataValue);

            // Render the end tag
            iTagBuilder.ToString(TagRenderMode.EndTag);

            // Add the I tag to the A tag
            aTagBuilder.InnerHtml += iTagBuilder.ToString();

            return new MvcHtmlString(aTagBuilder.ToString());
        }
    }

.Net Find all objects in current domain that implement IDisposable

using System;
using System.Linq;

namespace CsharpListInterfaceUsage
{
    class InterfaceListerDemo
    {
        public static void Main()
        {
            var interfaceType = typeof(IDisposable);

            var results = AppDomain.CurrentDomain
                                      .GetAssemblies()
                                      .SelectMany(x => x.GetTypes())
                                      .Where(interfaceType.IsAssignableFrom)
                                      .ToList();

            results.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(Type type)
        {
            Console.WriteLine(type.FullName);
        }
    }
}

.Net and C# simple image comparison using the AForge.Imaging library

To perform a simple image comparison test use the ImageComparer class. Input images are converted into bitmaps for the actual comparison.

The comparison uses the AForge.NET imaging library, it’s an open source project published under the GPL v3 license. The sample below uses the latest (to date) 2.2.5 version.

using System;
using System.Drawing;
using System.IO;
using AForge.Imaging;

namespace ImageCompare
{
    /// <summary>
    /// Image comparison class to match and rate if bitmapped images are similar.
    /// </summary>
    public static class ImageComparer
    {
        // The file extension for the generated Bitmap files
        private const string BitMapExtension = ".bmp";

        /// <summary>
        /// Compares the images.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="targetImage">The target image.</param>
        /// <param name="compareLevel">The compare level.</param>
        /// <param name="filepath">The filepath.</param>
        /// <param name="similarityThreshold">The similarity threshold.</param>
        /// <returns>Boolean result</returns>
        public static Boolean CompareImages(string image, string targetImage, double compareLevel, string filepath, float similarityThreshold)
        {
            // Load images into bitmaps
            var imageOne = new Bitmap(image);
            var imageTwo = new Bitmap(targetImage);

            var newBitmap1 = ChangePixelFormat(new Bitmap(imageOne), System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            var newBitmap2 = ChangePixelFormat(new Bitmap(imageTwo), System.Drawing.Imaging.PixelFormat.Format24bppRgb);

            newBitmap1 = SaveBitmapToFile(newBitmap1, filepath, image, BitMapExtension);
            newBitmap2 = SaveBitmapToFile(newBitmap2, filepath, targetImage, BitMapExtension);

            // Setup the AForge library
            var tm = new ExhaustiveTemplateMatching(similarityThreshold);

            // Process the images
            var results = tm.ProcessImage(newBitmap1, newBitmap2);

            // Compare the results, 0 indicates no match so return false
            if (results.Length <= 0)
            {
                return false;
            }

            // Return true if similarity score is equal or greater than the comparison level
            var match = results[0].Similarity >= compareLevel;

            return match;
        }

        /// <summary>
        /// Saves the bitmap automatic file.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="filepath">The filepath.</param>
        /// <param name="name">The name.</param>
        /// <param name="extension">The extension.</param>
        /// <returns>Bitmap image</returns>
        private static Bitmap SaveBitmapToFile(Bitmap image, string filepath, string name, string extension)
        {
            var savePath = string.Concat(filepath, "\\", Path.GetFileNameWithoutExtension(name), extension);

            image.Save(savePath, System.Drawing.Imaging.ImageFormat.Bmp);

            return image;
        }

        /// <summary>
        /// Change the pixel format of the bitmap image
        /// </summary>
        /// <param name="inputImage">Bitmapped image</param>
        /// <param name="newFormat">Bitmap format - 24bpp</param>
        /// <returns>Bitmap image</returns>
        private static Bitmap ChangePixelFormat(Bitmap inputImage, System.Drawing.Imaging.PixelFormat newFormat)
        {
            return (inputImage.Clone(new Rectangle(0, 0, inputImage.Width, inputImage.Height), newFormat));
        }
    }
}

The image comparison is run via a test harness:

using System;

namespace ImageCompare
{
    static class ImageComparerTester
    {
        static void Main()
        {
            // Filepath to the image directory
            const string dirpath = @"C:\Temp\";

            // The threshold is the minimal acceptable similarity between template candidate. 
            // Min (loose) is 0.0 Max (strict) is 1.0
            const float similarityThreshold = 0.50f;
            
            const string testImageOne = @"C:\Temp\ChartImg.png";
            const string testImageTwo = @"C:\Temp\ChartPic_000001.png";
            const string testImageThree = @"C:\Temp\ChartPic_000002.png";

            // Comparison level is initially set to 0.95
            // Increment loop in steps of .01
            for (var compareLevel = 0.95; compareLevel <= 1.00; compareLevel += 0.01)
            {
                // Run the tests
                var testOne = ImageComparer.CompareImages(testImageOne, testImageOne, compareLevel, dirpath, similarityThreshold);
                var testTwo = ImageComparer.CompareImages(testImageOne, testImageTwo, compareLevel, dirpath, similarityThreshold);
                var testThree = ImageComparer.CompareImages(testImageOne, testImageThree, compareLevel, dirpath, similarityThreshold);
                var testFour = ImageComparer.CompareImages(testImageTwo, testImageThree, compareLevel, dirpath, similarityThreshold);

                // Output the results
                Console.WriteLine("Test images for similarities at compareLevel: {0}", compareLevel);
                Console.WriteLine("Results for Image 1 compared to Image 1 - Expected: True : Actual {0}", testOne);
                Console.WriteLine("Results for Image 1 compared to Image 2 - Expected: True : Actual {0}", testTwo);
                Console.WriteLine("Results for Image 1 compared to Image 3 - Expected: False : Actual {0}", testThree);
                Console.WriteLine("Results for Image 2 compared to Image 3 - Expected: False : Actual {0}", testFour);
            }

            Console.WriteLine("End of comparison.");
            Console.ReadKey();
        }
    }
}

.Net IComparable example

using System;
using System.Collections.Generic;

namespace CsharpIComparableDemo
{
    class Program
    {
        static void Main()
        {
            var months = new List<Months>
                             {
                                 new Months() {Name = "January", Order = 1},
                                 new Months() {Name = "February", Order = 2},
                                 new Months() {Name = "March", Order = 3},
                                 new Months() {Name = "April", Order = 4},
                                 new Months() {Name = "May", Order = 5},
                                 new Months() {Name = "June", Order = 6},
                                 new Months() {Name = "July", Order = 7},
                                 new Months() {Name = "August", Order = 8},
                                 new Months() {Name = "September", Order = 9},
                                 new Months() {Name = "October", Order = 10},
                                 new Months() {Name = "November", Order = 11},
                                 new Months() {Name = "December", Order = 12}
                             };

            var monthsBare = new List<Months>
                             {
                                 new Months() {Name = "January"},
                                 new Months() {Name = "February"},
                                 new Months() {Name = "March"},
                                 new Months() {Name = "April"},
                                 new Months() {Name = "May"},
                                 new Months() {Name = "June"},
                                 new Months() {Name = "July"},
                                 new Months() {Name = "August"},
                                 new Months() {Name = "September"},
                                 new Months() {Name = "October"},
                                 new Months() {Name = "November"},
                                 new Months() {Name = "December"}
                             };

            months.Sort();

            months.ForEach(Print);

            Console.WriteLine();

            monthsBare.Sort();

            monthsBare.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(Months month)
        {
            Console.WriteLine("{0} {1}", month.Name, month.Order);
        }
    }

    public class Months : IComparable<Months>
    {
        public string Name { get; set; }
        public int Order { get; set; }

        public int CompareTo(Months month)
        {
            return Order == month.Order ? String.Compare(Name, month.Name, StringComparison.Ordinal) : month.Order.CompareTo(Order);
        }
    }
}

.Net Linq GroupBy anagram comparer example

using System;
using System.Collections.Generic;
using System.Linq;

namespace CsharpGroupByComparer
{
    class GroupByComparer
    {
        static void Main(string[] args)
        {
            var anagrams = new List<string> { "disks", "skids", "freed", "defer", "begin", "being", "note", "xxxx", };

            var results = anagrams.GroupBy(x => x.ToLower(), new AnagramComparer()).Where(x => x.Count() > 1).ToList();

            results.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(IGrouping<string, string> results)
        {
            foreach (var result in results)
                Console.WriteLine(result);
        }

        private class AnagramComparer : IEqualityComparer<string>
        {
            public bool Equals(string a, string b)
            {
                return GetString(a) == GetString(b);
            }

            public int GetHashCode(string obj)
            {
                return GetString(obj).GetHashCode();
            }

            private static string GetString(string word)
            {
                return new string(word.ToCharArray().OrderBy(x => x).ToArray());
            }
        }
    }
}

.Net Skip<> and Take<> example

using System;
using System.Collections.Generic;
using System.Linq;

namespace CsharpSkipTakeExample
{
    static class SkipTakeDemo
    {
        static void Main(string[] args)
        {
            var months = new List<string>
                           {
                               "January",
                               "February",
                               "March",
                               "April",
                               "May",
                               "June",
                               "July",
                               "August",
                               "September",
                               "October",
                               "November",
                               "December"
                           };

            // Get the first 6 months
            var firstSixMonths = months.GetRange(0, 6);

            firstSixMonths.ForEach(Print);

            Console.WriteLine();

            // Take the first 3 months
            var firstThreeMonths = months.Take(3).ToList();

            firstThreeMonths.ForEach(Print);

            Console.WriteLine();

            // Months ending with y
            var monthsEndingWithY = months.TakeWhile(x => x.EndsWith("y")).ToList();

            monthsEndingWithY.ForEach(Print);

            Console.WriteLine();

            // Skip the first Month by condition
            var skipTheFirstMonth = months.SkipWhile(x => x.StartsWith("J")).ToList();

            skipTheFirstMonth.ForEach(Print);

            Console.ReadKey();
        }

        private static void Print(string input)
        {
            Console.WriteLine(input);
        }
    }
}

.Net List<>.TrueForAll example

using System;
using System.Collections.Generic;

namespace CsharpTrueForAll
{
    public static class TrueForAllDemo
    {
        public static void Main()
        {
            var countries = new List<string> {"England", "Scotland", "Ireland", "Wales"};

            Console.WriteLine(countries.TrueForAll(CheckEnding));

            Console.ReadKey();
        }

        private static bool CheckEnding(string input)
        {
            return input.ToLower().EndsWith("land");
        }
    }
}

A simple ASP.Net MVC HTML Helper to truncate a string at an arbitrary length

public static MvcHtmlString DisplayNewsSearchSummary(this HtmlHelper htmlHelper, string input, int requiredLength, string ending = "...")
{
    // Validate and sanity check first...

   var requiredtext = input.Substring(0, requiredLength - 1);

   var ouputtext = string.Concat(requiredtext.Substring(0, requiredtext.LastIndexOf(' ')), ending);

   return new MvcHtmlString(descriptionText);
}