#747 – Turning Off All Caps Menus in Visual Studio 2012

One of the changes in Visual Studio 2012 was to render the main menus in all caps.  This was done to better match the new Metro (Windows Store) style of user interface, used across other Microsoft products.  (E.g. Office 2013 or the Bing web site).

747-001

However, many people have argued that using all caps make the user interface less readable and constitutes bad typography.

If you prefer using upper and lowercase in the main menu, you can turn off the all caps by adding a value in the registry.

In the key HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\11.0\General, create a DWORD value named SuppressUppercaseConversion and set its value to 1.

You’ll now get upper and lowercase in the menus.

747-002

#746 – Get a Free Copy of Visual Studio 2012

You can start using C# to develop applications by using one of the Visual Studio 2012 Express editions.  Each of the editions listed below is free and allows you to create applications for the listed platform.

  • Visual Studio Express 2012 for Web
  • Visual Studio Express 2012 for Windows 8  (Windows Store apps)
  • Visual Studio Express 2012 for Windows Desktop
  • Visual Studio Express 2012 for Windows Phone

Additionally, you can get a free copy of Visual Studio Team Foundation Server Express 2012, which allows up to five developers to do source code control, work item tracking, and build automation.

#745 – Use ReSharper to Increase Your Productivity in Visual Studio

Here’s a handy tool that will help you to be more productive when writing C# code in Visual Studio.  Resharper, or R#, by JetBrain.

Some of the features provided by Resharper include:

  • Quickly navigating to a type, file, or member of a type
  • Navigate to a the definition of a member or the places in code where a member is used
  • Automatic decompilation of third-party code
  • Code inspections and checking
  • Suggestions for code refactoring, includes classes, methods and code segments
  • Alt-Enter to quickly fix coding errors or to refactor code
  • Define custom code patterns to warn about
  • Inspect variables and class members to see where/how they are used
  • Removal of unused assembly references
  • Many more features

Take a look at ReSharper.  A C# license is $149 for an individual developer, or $249 for a commercial license.

#744 – The Purpose of Inheritance

Inheritance in C# (and .NET) is the idea of designing a class that reuses the implementation of an existing class.

The primary purpose of inheritance is to reuse code from an existing class.  Inheritance allows you to create a new class that starts off by including all data and implementation details of the base class.  You can then extend the derived class, to add data or behavior.

You can also use inheritance to modify the behavior of an existing class.  The code below shows a QuietDog class that does everything that a normal Dog does, but barks quietly.

    public class Dog
    {
        public string Name { get; set; }

        public void Bark()
        {
            Console.WriteLine("Woof");
        }

        public void Fetch()
        {
            Console.WriteLine("Fetching !");
        }
    }

    public class QuietDog : Dog
    {
        public new void Bark()
        {
            Console.WriteLine(".. silence ..");
        }
    }

#743 – ASCII Art Generator

Here’s a little ASCII Art generator that I wrote in C#.  Merry Christmas!

Main program, which accepts full path to image file to be converted:

    class Program
    {
        /// <summary>
        /// Usage:
        ///   Arg 1 - Full path to bitmap file (e.g. JPG, PNG)
        ///   Arg 2 - Width of target image, in # characters (e.g. 120)
        ///   Output: File with same name as input file but .txt extension
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 2)
                {
                    Console.WriteLine("Usage:");
                    Console.WriteLine("  AscArt filename output-width [diagLog]");
                }
                else
                {
                    string inputFile = args[0];
                    int outputWidth = int.Parse(args[1]);

                    FileInfo fi = new FileInfo(inputFile);
                    if (!fi.Exists)
                        throw new Exception(string.Format("File {0} not found", inputFile));
                    string outputFile = Path.Combine(fi.DirectoryName, Path.GetFileNameWithoutExtension(inputFile) + ".txt");

                    Bitmap bmInput = new Bitmap(inputFile);

                    if (outputWidth > bmInput.Width)
                        throw new Exception("Output width must be <= pixel width of image");

                    // Generate the ASCII art
                    AscArt.GenerateAsciiArt(bmInput, outputFile, outputWidth);
                }
            }
            catch (Exception xx)
            {
                Console.WriteLine(string.Format("Fatal exception: {0}", xx));
            }
        }
    }

Here’s the source code for the AscArt class:

    public static class AscArt
    {
        // Typical width/height for ASCII characters
        private const double FontAspectRatio = 0.6;

        // Available character set, ordered by decreasing intensity (brightness)
        private const string OutputCharSet = "@%#*+=-:. ";

        // Alternate char set uses more chars, but looks less realistic
        private const string OutputCharSetAlternate = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\"^`'. ";

        public static void GenerateAsciiArt(Bitmap bmInput, string outputFile, int outputWidth)
        {
            // pixelChunkWidth/pixelChunkHeight - size of a chunk of pixels that will
            // map to 1 character.  These are doubles to avoid progressive rounding
            // error.
            double pixelChunkWidth = (double)bmInput.Width / (double)outputWidth;
            double pixelChunkHeight = pixelChunkWidth / FontAspectRatio;

            // Calculate output height to capture entire image
            int outputHeight = (int)Math.Round((double)bmInput.Height / pixelChunkHeight);

            // Generate output image, row by row
            double pixelOffSetTop = 0.0;
            StringBuilder sbOutput = new StringBuilder();

            for (int row = 1; row <= outputHeight; row++)
            {
                double pixelOffSetLeft = 0.0;

                for (int col = 1; col <= outputWidth; col++)
                {
                    // Calculate brightness for this set of pixels by averaging
                    // brightness across all pixels in this pixel chunk
                    double brightSum = 0.0;
                    int pixelCount = 0;
                    for (int pixelLeftInd = 0; pixelLeftInd < (int)pixelChunkWidth; pixelLeftInd++)
                        for (int pixelTopInd = 0; pixelTopInd < (int)pixelChunkHeight; pixelTopInd++)
                        {
                            // Each call to GetBrightness returns value between 0.0 and 1.0
                            int x = (int)pixelOffSetLeft + pixelLeftInd;
                            int y = (int)pixelOffSetTop + pixelTopInd;
                            if ((x < bmInput.Width) && (y < bmInput.Height))
                            {
                                brightSum += bmInput.GetPixel(x, y).GetBrightness();
                                pixelCount++;
                            }
                        }

                    // Average brightness for this entire pixel chunk, between 0.0 and 1.0
                    double pixelChunkBrightness = brightSum / pixelCount;

                    // Target character is just relative position in ordered set of output characters
                    int outputIndex = (int)Math.Floor(pixelChunkBrightness * OutputCharSet.Length);
                    if (outputIndex == OutputCharSet.Length)
                        outputIndex--;

                    char targetChar = OutputCharSet[outputIndex];

                    sbOutput.Append(targetChar);

                    pixelOffSetLeft += pixelChunkWidth;
                }
                sbOutput.AppendLine();
                pixelOffSetTop += pixelChunkHeight;
            }

            // Dump output string to file
            File.WriteAllText(outputFile, sbOutput.ToString());
        }
    }

So converting this image:
SeanHeadShot
Gives us the following:

743-001

Enjoy!

#742 – A Simple Example of Inheritance

Here’s a simple example of inheritance in C#.

The Dog class has a Name property and a Bark method.

    public class Dog
    {
        public string Name { get; set; }

        public void Bark()
        {
            Console.WriteLine(Name + " : Woof");
        }
    }

The Terrier class inherits from Dog and adds a HuntVermin method.

    public class Terrier : Dog
    {
        public void HuntVermin()
        {
            Console.WriteLine(Name + " off to find vermin");
        }
    }

An object of type Dog has access to the Name property and the Bark method.  An object of type Terrier also has access to Name and Bark and also to the HuntVermin method.

            Dog d = new Dog();
            d.Name = "Kirby";
            d.Bark();

            Terrier t = new Terrier();
            t.Name = "Jack";
            t.Bark();
            t.HuntVermin();

742-001

#741 – The Basics of Inheritance

Inheritance in C# (and .NET) is the idea of designing a class that reuses the implementation of an existing class.  All public members in the original (parent) class become public members in the new (child) class.  (Except for constructors).  Both data and behavior are inherited by the child class.

Every class in C# must inherit from exactly one class.  By default, a class inherits from System.Object.  You can instead indicate the desired parent class by specifying it after a colon (:) when defining the new class.

public class Terrier : Dog
{
}

The class being inherited from is known as the base class or parent class.  The new class is known as the derived class or child class.

An instance of the child class automatically has access to all public members of the base class, as well as its own public members.

#740 – Short vs. Long Weak References

You can create a WeakReference object that refers to a regular reference-typed object and lets you discover whether the original object has been garbage collected or not.  You can use the Target property of the WeakReference to reference the original object, if it’s still alive.

By default, a WeakReference object creates a short weak reference–the target of the weak reference becomes null and the IsAlive property reports false as soon as the object’s finalizer is called, but potentially before the object is actually garbage collected.

You can also create a long weak reference by passing a value of true as the second parameter to the WeakReference constructor.  The Target will remain non-null after the object has been finalized, up until the point in time when it actually gets garbage collected.  In this way, you retain access to an object that has been finalized, but not collected.

#739 – Avoid Accessing an Object After Its Been Finalized

A finalizer should not create a new reference to the object being finalized.  Below is an example where doing this leads to the ability to reference the object after it’s been finalized.

This is an example of questionable code–in general, it’s dangerous to reconstitute an object after it’s been finalized.

In the Dog class, we save a reference to the object being finalized.

    public class Dog
    {
        public static Dog KeepDogRef;

        public string Name { get; set; }

        public Dog(string name)
        {
            Name = name;
        }

        ~Dog()
        {
            Console.WriteLine("Dog destructor for " + Name + " called");
            Dog.KeepDogRef = this;
        }

        public void Bark()
        {
            Console.WriteLine(Name + " : Woof");
        }
    }

In main program, we reconstitute a Dog object after it’s been finalized.

            Dog dog = new Dog("Bowser");

            WeakReference dogRef = new WeakReference(dog);

            // Unref Bowser
            dog = null;
            GC.Collect();
            GC.WaitForPendingFinalizers();

            // Bowser is gone
            Console.WriteLine(string.Format("Object still alive: {0}", dogRef.IsAlive));

            // Hey, Bowser is alive again!
            Dog newRef = Dog.KeepDogRef;
            newRef.Bark();

739-001

#738 – You Shouldn’t Explicitly Force Garbage Collection

For purposes of understanding what happens when objects get garbage collected, you can force garbage collection to happen by calling the GC.Collect method.  Calling this method in production code is almost always a bad idea.

The garbage collector is finely tuned for maximum performance and when you call GC.Collect explicitly, you disturb that tuning and make the garbage collector less efficient.

When you feel that you need to call GC.Collect in order to explicit release objects, it’s generally a sign of poor design in some area of your code.  (E.g. Not making proper use of a Dispose method on an object when you are done using it).