Fake Latin Generator in ASP.NET MVC

While designing HTML templates, I, like everyone else, frequently use filler text to fill up space before content exists. I’ve been doing this a lot lately in ASP.NET MVC 2. Having static fake Latin filler text in a web application while developing is nice but having random fake Latin text is more useful for a couple of reasons:

  1. It forces your page to render with different lengths of text which can help find bugs
  2. It’s more amusing and beats staring at the exact same text

Since I’m working in ASP.NET MVC mostly, I’ve used C# to create several extension methods on the HtmlHelper object. This enables me to generate fake Latin text inline in HTML and Views.

<h1><%= Html.FakeLatinTitle(5) %></h1>
<p>
    <%= Html.FakeLatinParagraph(500) %>
</p>

Here’s the C# source behind FakeLatinParagraph(), FakeLatinParagraphs() and FakeLatinTitle():

using System;
using System.Web.Mvc;
using System.Text;

namespace Web.Extensions
{
    public static class HtmlHelperExtensions
    {
        #region Private Statics

        private static int _seed;

        #endregion

        #region Extension Methods

        public static string FakeLatinParagraph(this HtmlHelper helper, int wordCount)
        {
            string[] dictionary = "lorem ipsum dolor sit amet consectetuer adipiscing elit sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi Ut wisi enim ad minim veniam quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi".Split(' ');
            StringBuilder words = new StringBuilder();
            Random rand = null;
            string paragraph = string.Empty;

            if (HtmlHelperExtensions._seed >= int.MaxValue - 1000)
                HtmlHelperExtensions._seed = 0;

            rand = new Random(HtmlHelperExtensions._seed += DateTime.Now.Millisecond);

            for (int n = 0; n < wordCount; n++)
                words.AppendFormat("{0} ", dictionary[rand.Next(0, dictionary.Length)]);

            paragraph = words.ToString();
            paragraph = string.Format("{0}{1}.", char.ToUpperInvariant(paragraph[0]), paragraph.Substring(1).TrimEnd());

            return paragraph;
        }

        public static string FakeLatinParagraphs(this HtmlHelper helper, int paragraphCount, int wordsPerParagraph, string beforeParagraph, string afterParagraph)
        {
            StringBuilder paragraphs = new StringBuilder();

            for (int n = 0; n < paragraphCount; n++)
            {
                paragraphs.AppendFormat("\n{0}\n", beforeParagraph);
                paragraphs.AppendFormat("\t{0}", HtmlHelperExtensions.FakeLatinParagraph(helper, wordsPerParagraph));
                paragraphs.AppendFormat("\n{0}\n", afterParagraph);
            }

            return paragraphs.ToString();
        }

        public static string FakeLatinTitle(this HtmlHelper helper, int wordCount)
        {
            string title = HtmlHelperExtensions.FakeLatinParagraph(helper, wordCount);

            title = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(title);
            title = title.Substring(0, title.Length - 1); // kill period from paragraph
            return title;
        }

        #endregion
    }
}

Don’t forget to include the namespace where the extension methods exist anywhere where you want to have access to them.

using System;
using System.Web;
using System.Web.Mvc;
// ... whatever other namespaces
using Web.Extensions; // YOU NEED ME!

If you want a set of extension methods to be available on every ASP.NET MVC View, you can add the reference in the web.config file.

<!-- SNIPPET OF WEB CONFIG -->
<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
    <namespaces>
        <add namespace="System.Web.Mvc"/>
        <add namespace="System.Web.Mvc.Ajax"/>
        <add namespace="System.Web.Mvc.Html"/>
        <add namespace="System.Web.Routing"/>
        <add namespace="System.Linq"/>
        <add namespace="System.Collections.Generic"/>
        <add namespace="Web.Extensions"/> <!-- EXTENSION METHODS NAMESPACE -->
    </namespaces>
</pages>
<!-- END SNIPPET OF WEB CONFIG (don't replace your entire web.config file with only this) -->

Sql CE Browser v1.1.0

During my continued work with Sql Compact Edition, I’ve been improving Sql CE Browser.

Download the latest version of Sql CE Browser v1.1.0 (free, 2,283 KB).

Features:

  • Open regular and encrypted/passworded databases for viewing or editing
  • Write and work with any number of queries at once via tabs
  • SQL syntax highlighting and SQL syntax verification
  • Explore columns, keys, and indexes

Updates in v1.1.0:

  • Threaded database actions
  • Refresh database button
  • Smarter database/query open dialogs
  • Updated icons
  • Support for multiple primary keys
  • UI updates for easier usage
  • Installer (stand-alone version coming)
Sql CE Browser beta main screen

Sql CE Browser beta main screen

Browse and edit data in Microsoft SQL CE databases

I’ve been working on a little project that requires Microsoft SQL CE databases and couldn’t find anything that did quite what I wanted. SQL Server Management Studio allows for design of CE databases but not for browsing/editing data easily.

Sql CE Browser v1.1, updated (download now for free, 2,283 KB) allows you to browse and edit data in SQL CE databases.

Features:

  • Open regular and encrypted/passworded databases for viewing or editing
  • Write and work with any number of queries at once via tabs
  • SQL syntax highlighting and SQL syntax verification
  • Explore columns, keys, and indexes
Sql CE Browser main window

Sql CE Browser main window

Sql CE Browser table properties

Sql CE Browser table properties

Common name prefixes, titles and honorifics

Every time I need a list of name prefixes, I never have one handy. Here’s a list of common English honorifics that I’m slowly compiling:

  • Ms
  • Miss
  • Mrs
  • Mr
  • Master
  • Rev (Reverend)
  • Fr (Father)
  • Dr (Doctor)
  • Atty (Attorney)
  • Prof (Professor)
  • Hon (Honorable)
  • Pres (President)
  • Gov (Governor)
  • Coach
  • Ofc (Officer)

Here are some others titles are less common:

  • Msgr (Monsignor)
  • Sr (Sister)
  • Br (Brother)
  • Supt (Superintendent)
  • Rep (Representative)
  • Sen (Senator)
  • Amb (Ambassador)
  • Treas (Treasurer)
  • Sec (Secretary)
  • Pvt (Private)
  • Cpl (Corporal)
  • Sgt (Sargent)
  • Adm (Administrative)
  • Maj (Major)
  • Capt (Captain)
  • Cmdr (Commander)
  • Lt (Lieutenant)
  • Lt Col (Lieutenant Colonel)
  • Col (Colonel)
  • Gen (General)

Make an image black and white in c#

I’ve gone on a strange image manipulation kick in c# recently. Partly because I needed blurring method for something (then pixelation spawned from that) and then partially because it was fun. Here’s how to remove color from an image in c#:

private static Bitmap BlackAndWhite(Bitmap image, Rectangle rectangle)
{
    Bitmap blackAndWhite = new System.Drawing.Bitmap(image.Width, image.Height);

    // make an exact copy of the bitmap provided
    using(Graphics graphics = System.Drawing.Graphics.FromImage(blackAndWhite))
        graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

    // for every pixel in the rectangle region
    for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width && xx < image.Width; xx++)
    {
        for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height && yy < image.Height; yy++)
        {
            // average the red, green and blue of the pixel to get a gray value
            Color pixel = blackAndWhite.GetPixel(xx, yy);
            Int32 avg = (pixel.R + pixel.G + pixel.B) / 3;

            blackAndWhite.SetPixel(xx, yy, Color.FromArgb(0, avg, avg, avg));
        }
    }

    return blackAndWhite;
}

The BlackAndWhite() method takes a look at every pixel in the region and averages the red, green and blue values to get a gray value. Once a gray value is determined, the pixel is set to that color.

Joe's Crab Shack in San Francisco

Joe's Crab Shack in San Francisco

Black and White Joe's Crab Shack in San Francisco

Black and White Joe's Crab Shack in San Francisco

If you want to make the entire image black and white and not just a region (rectangle), then overload the BlackAndWhite() method like this:

private static Bitmap BlackAndWhite(Bitmap image)
{
    return BlackAndWhite(image, new Rectangle(0, 0, image.Width, image.Height));
}

Download the original Joe’s Crab Shack image.

*Update: I was poking around on the Internet, looking at things and stuff and found a better greyscale implementation (read: faster, much faster and a bit more complex) from Switch On The Code. Check it out:

public static Bitmap MakeGrayscale3(Bitmap original)
{
   //create a blank bitmap the same size as original
   Bitmap newBitmap = new Bitmap(original.Width, original.Height);

   //get a graphics object from the new image
   Graphics g = Graphics.FromImage(newBitmap);

   //create the grayscale ColorMatrix
   ColorMatrix colorMatrix = new ColorMatrix(
      new float[][]
      {
         new float[] {.3f, .3f, .3f, 0, 0},
         new float[] {.59f, .59f, .59f, 0, 0},
         new float[] {.11f, .11f, .11f, 0, 0},
         new float[] {0, 0, 0, 1, 0},
         new float[] {0, 0, 0, 0, 1}
      });

   //create some image attributes
   ImageAttributes attributes = new ImageAttributes();

   //set the color matrix attribute
   attributes.SetColorMatrix(colorMatrix);

   //draw the original image on the new image
   //using the grayscale color matrix
   g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
      0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);

   //dispose the Graphics object
   g.Dispose();
   return newBitmap;
}

Pixelate an image with c#

Pixelating an image in c# is on par with blurring an image – not terribly complex. This method accepts an image, a pixelate region (rectangle), a pixelate size and returns a bitmap.

private static Bitmap Pixelate(Bitmap image, Rectangle rectangle, Int32 pixelateSize)
{
    Bitmap pixelated = new System.Drawing.Bitmap(image.Width, image.Height);

    // make an exact copy of the bitmap provided
    using (Graphics graphics = System.Drawing.Graphics.FromImage(pixelated))
        graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

    // look at every pixel in the rectangle while making sure we're within the image bounds
    for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width && xx < image.Width; xx += pixelateSize)
    {
        for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height && yy < image.Height; yy += pixelateSize)
        {
            Int32 offsetX = pixelateSize / 2;
            Int32 offsetY = pixelateSize / 2;

            // make sure that the offset is within the boundry of the image
            while (xx + offsetX >= image.Width) offsetX--;
            while (yy + offsetY >= image.Height) offsetY--;

            // get the pixel color in the center of the soon to be pixelated area
            Color pixel = pixelated.GetPixel(xx + offsetX, yy + offsetY);

            // for each pixel in the pixelate size, set it to the center color
            for (Int32 x = xx; x < xx + pixelateSize && x < image.Width; x++)
                for (Int32 y = yy; y < yy + pixelateSize && y < image.Height; y++)
                    pixelated.SetPixel(x, y, pixel);
        }
    }

    return pixelated;
}

The pixelate method looks at ever block of pixels in the pixelate size, grabs the middle pixel and then sets all of the pixels in the block to that same color. If you don’t use the middle pixel, the image ends up shifting (my initial version looked at the top-left pixel.)

Dad at Christmas

Dad at Christmas

Pixelated Dad at Christmas

Pixelated Dad at Christmas

If you want to pixelate the whole image, just use the bounds of the original image as the pixelate rectangle. Here’s an example of how to overload the Pixelate() method:

private static Bitmap Pixelate(Bitmap image, Int32 blurSize)
{
    return Pixelate(image, new Rectangle(0, 0, image.Width, image.Height), blurSize);
}

Download original dad image.

Blur an image with c#

Blurring an image with c# is pretty simple. I was messing around with something one night and needed to blur certain regions of JPGs that I was processing. This method accepts an image, a blur region (rectangle), a blur size and returns a blurred bitmap.

private static Bitmap Blur(Bitmap image, Rectangle rectangle, Int32 blurSize)
{
    Bitmap blurred = new Bitmap(image.Width, image.Height);

    // make an exact copy of the bitmap provided
    using(Graphics graphics = Graphics.FromImage(blurred))
        graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

    // look at every pixel in the blur rectangle
    for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width; xx++)
    {
        for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height; yy++)
        {
            Int32 avgR = 0, avgG = 0, avgB = 0;
            Int32 blurPixelCount = 0;

            // average the color of the red, green and blue for each pixel in the
            // blur size while making sure you don't go outside the image bounds
            for (Int32 x = xx; (x < xx + blurSize && x < image.Width); x++)
            {
                for (Int32 y = yy; (y < yy + blurSize && y < image.Height); y++)
                {
                    Color pixel = blurred.GetPixel(x, y);

                    avgR += pixel.R;
                    avgG += pixel.G;
                    avgB += pixel.B;

                    blurPixelCount++;
                }
            }

            avgR = avgR / blurPixelCount;
            avgG = avgG / blurPixelCount;
            avgB = avgB / blurPixelCount;

            // now that we know the average for the blur size, set each pixel to that color
            for (Int32 x = xx; x < xx + blurSize && x < image.Width && x < rectangle.Width; x++)
                for (Int32 y = yy; y < yy + blurSize && y < image.Height && y < rectangle.Height; y++)
                    blurred.SetPixel(x, y, Color.FromArgb(avgR, avgG, avgB));
        }
    }

    return blurred;
}

The method takes a look at every pixel within the blur rectangle and samples the reds, greens and blues within the blur size to figure out an average. Then it sets every pixel within the blur size square to the average color.

Jellyfish at the Monterey Aquarium

Jellyfish at the Monterey Aquarium

Blurred jellyfish at the Monterey Aquarium

Blurred jellyfish at the Monterey Aquarium

If you want to blur the whole image, just use the bounds of the original image as the blur rectangle. Here’s an example of how to overload the Blur() method:

private static Bitmap Blur(Bitmap image, Int32 blurSize)
{
    return Blur(image, new Rectangle(0, 0, image.Width, image.Height), blurSize);
}

Download original jellyfish image.