Magical ConsoleManager class

by abutler 19. August 2011 14:51

Ever want to add a console window to a Forms app?  How about a cool console window for some output from your ASP.Net worker process?  Ok, it's not that cool, but here's a class that I wrote a while back that will do it.

 

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security;
using System.Text;

/// <summary>
/// Class for attaching a Console window to the current process
/// </summary>	
internal class ConsoleManager : IDisposable
{
	#region Win32 API functions
	[DllImport("kernel32.dll")]
	private static extern bool AllocConsole();
	[DllImport("kernel32.dll")]
	private static extern bool FreeConsole();
	[DllImport("kernel32.dll")]
	private static extern IntPtr GetConsoleWindow();
	#endregion

	#region singleton
	/// <summary>
	/// Nested class for accessing the singleton object
	/// </summary>
	class Nested
	{
		// Explicit static constructor to tell C# compiler
		// not to mark type as beforefieldinit (lazy loading)
		static Nested()
		{
		}
		internal static readonly ConsoleManager Instance = new ConsoleManager();
	}
	#endregion

	#region constructors
	private ConsoleManager()
	{
	}
	#endregion

	#region instance methods
	/// <summary>
	/// Returns true if a console window has been attached
	/// </summary>
	private bool HasConsole
	{
		get { return GetConsoleWindow() != IntPtr.Zero; }
	}

	/// <summary>
	/// Creates a new console instance if the process is not attached to a console already.
	/// </summary>
	/// <returns>true if a Console window was attached as a result of this call</returns>
	private bool ShowConsole()
	{
		bool consoleAllocated = false;
		if (!HasConsole)
		{
			AllocConsole();
			Console.Title = "Diagnostics Console";
			consoleAllocated = true;
		}
		return consoleAllocated;
	}

	/// <summary>
	/// If the process has a console attached to it, it will be detached and no longer visible. 
	/// Writing to the System.Console is still possible, but no output will be shown.
	/// </summary>
	/// <remarks>True if the Console window was freed / hidden</remarks>
	private bool HideConsole()
	{
		bool consoleHidden = false;
		if (HasConsole)
		{
			FreeConsole();
			consoleHidden = true;
		}
		return consoleHidden;
	}
	#endregion

	#region static methods
	/// <summary>
	/// Shows a Console window
	/// </summary>
	/// <returns>True if the Console window was shown as a result of this call</returns>
	public static bool Show()
	{
		return Nested.Instance.ShowConsole();
	}

	/// <summary>
	/// Hides the Console window
	/// </summary>
	/// <returns>True if the Console windows was hidden as a result of this call</returns>
	public static bool Hide()
	{
		return Nested.Instance.HideConsole();
	}

	/// <summary>
	/// Shows the console window if it is currently hidden, OR hides it when it is currently visible
	/// </summary>
	public static void Toggle()
	{
		if (Nested.Instance.HasConsole)
		{
			Nested.Instance.HideConsole();
		}
		else
		{
			Nested.Instance.ShowConsole();
		}
	}
	#endregion

	#region cleanup
	private bool _disposed;
	~ConsoleManager()
	{
		Dispose(false);
	}

	public void Dispose()
	{
		Dispose(true);
		GC.SuppressFinalize(this);
	}

	protected virtual void Dispose(bool disposing)
	{
		if (!_disposed)
		{
			if (disposing)
			{
				// Dispose managed resources here.
			}
			// Dispose unmanaged resources here.				
			HideConsole();
		}
		_disposed = true;
	}
	#endregion
}

Overriding object.GetHashCode()

by abutler 25. May 2011 10:07

Say you are building a dictionary of data, and you want the key to be a complex object.  The easy way would be to do something like this:

 

Dictionary<string, string> dict = new Dictionary<string, string>();
dict.Add(someObject.Prop1 + ";" + someObject.Prop2, "some value here");

But that just feels wrong, there are a lot of things that can go wrong.  How will this work for objects that have many properties?  Is "Prop1.SubProp1,Prop1.SubProp2,Prop1.SubProp3;Prop2.SubProp1,Prop2.SubProp2,Prop2.SubProp3" really the way to go?  Maybe if you're building a commissions system for an MLM company or something, but not for real applications.  Enter object.GetHashCode()

 

Here's a link that provides some really good background on GetHashCode():

http://blogs.msdn.com/b/ericlippert/archive/2011/02/28/guidelines-and-rules-for-gethashcode.aspx

 

Ever wonder why this is a virtual method in the first place?  Answered in the article above, quoted below:

 

I think if we were redesigning the type system from scratch today, hashing might be done differently, perhaps with an IHashable interface. But when the CLR type system was designed there were no generic types and therefore a general-purpose hash table needed to be able to store any object.

 

Okay, so how to implement a decent GetHashCode() method yourself?  Here is a very smart guy's answer:

http://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode/263416#263416

 

Code excerpt from the link:

 

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Suitable nullity checks etc, of course :)
        hash = hash * 23 + field1.GetHashCode();
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

 

This works pretty well, and any time you have prime numbers in your code people will think you're hardcore.  Or they'll recognize that you copied the code from stackoverflow.com, but it's from the #1 user there, so you're good.

 

What to do with null fields though?  Be careful with that one, one suggestion I found while doing a search made it seem like it was okay to use base.GetHashCode if one of your fields is null.  Try to view the implementation of object.GetHashCode() using Reflector (or some other tool, since reflector is bugging me about the free version expiring).  You'll see there that the implementation is internal in the CLR code.  But this guy has it all figured out:

http://stackoverflow.com/questions/720177/default-implementation-for-object-gethashcode/720196#720196

 

But basically what we need to understand about object.GetHashCode() is that it returns a unique code for the object, so two "equal" objects will NOT have the same code.  So, not what you want to use if you have null fields.  Just use 0 in that case:

 

public override int GetHashCode()
{
    unchecked // Overflow is fine, just wrap
    {
        int hash = 17;
        // Example of how to deal with a null field
        hash = hash * 23 + (field1 == null ? 0 : field1.GetHashCode());
        // not this way
        // hash = hash * 23 + (field1 == null ? base.GetHashCode() : field1.GetHashCode());
        hash = hash * 23 + field2.GetHashCode();
        hash = hash * 23 + field3.GetHashCode();
        return hash;
    }
}

Real life Caesar Cipher

by chriscap 7. April 2011 15:31

I didn't think it was possible...

 

While going through some legacy code, I found a real life caesar cipher for encryption.  I guess I shouldn't be surprised.

 

strNewChar = Chr$(Asc(Mid$(vstrInString, intPos, 1)) + Asc(Mid$(gstrENCRYPT_DECRYPT_KEY, intKeyPos, 1)) - 32)

 

My colleague informs me it could be worse.  They could have used the generic Mid instead of Mid$.  Because when you've got crappy encryption, it should at least be fast?

Apparently I don't understand iterator blocks

by abutler 7. April 2011 14:37

Ran into something interesting today, which revealed a big hole in my knowledge of iterator blocks / the yield statement.  Sample code:

 

 

using System;
using System.Collections.Generic;

class Program
{
	static void Main(string[] args)
	{
		SplitChars(null);
		
		Console.ReadKey();
	}		

	static IEnumerable<char> SplitChars(string input)
	{
		if (input == null)
			throw new ArgumentNullException("input");

		for (int i = 0; i < input.Length; i++)
		{
			yield return input[i];
		}

		Console.WriteLine(input);
	}
}

 

 

I expected this to fail the method's argument validation.  It runs without throwing the exception.  Turns out a quick trip to StackOverflow revealed what is really going here.  Turns out until you use the result of an block as an iterator block, nothing is executed.  So if we run the sample code like this:

 

 

using System;
using System.Collections.Generic;

class Program
{
	static void Main(string[] args)
	{
		foreach (char c in SplitChars(null))
		{
			Console.WriteLine(c);
		}
		Console.ReadKey();
	}		

	static IEnumerable<char> SplitChars(string input)
	{
		if (input == null)
			throw new ArgumentNullException("input");

		for (int i = 0; i < input.Length; i++)
		{
			yield return input[i];
		}

		Console.WriteLine(input);
	}
}

 

 

Now we get the expected exception.  I'm probably the only one who would be surprised by this behavior, although it makes sense now that I have read about how the code generation involved, etc.

Some links on this subject:

http://stackoverflow.com/questions/2504352/c-yield-in-nested-method/2504369#2504369

http://blogs.msdn.com/b/oldnewthing/archive/2008/08/12/8849519.aspx

The magic factory class

by abutler 1. April 2011 12:32

An all-code post, just paste the whole thing into a console app

 

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;

class Program
{
	static void Main(string[] args)
	{
		// Here's the usage of a "traditional" factory, which returns objects that implement a common interface.
		// This is a great pattern for a lot of different scenarios.
		// The only downside is that you have to update your factory class whenever you add a new class.
		TraditionalFactory.Create("A_ID").DoIt();
		TraditionalFactory.Create("B_ID").DoIt();		
		Console.ReadKey();

		// But what if we make a class that uses reflection to find attributes of classes it can create? Reflection!
		// This works great and now all we have to do is add an attribute to new classes and this thing will just work.
		// (It could also be more generic in its input / output, but I simplified it for this example)
		ReflectionFactory.Create("A_ID").DoIt();
		ReflectionFactory.Create("B_ID").DoIt();
		// Wait, that's great and all, but everyone always says reflection is so slow, and this thing's going to reflect 
		// on every object creation...that's not good right?
		Console.ReadKey();

		// So I created this magical factory which gives the speed of the traditional factory combined with the flexibility 
		// of the reflection-based factory.
		// The reflection done here is only performed once. After that, it is as if the Create() method is using a switch
		// statement (plus a delegate invocation, but we'll ignore that little detail)		
		Factory<string, IDoSomething>.Create("A_ID").DoIt();
		Factory<string, IDoSomething>.Create("B_ID").DoIt();

		Console.ReadKey();
	}
}

class TraditionalFactory
{
	public static IDoSomething Create(string id)
	{
		switch (id)
		{
			case "A_ID":
				return new A();
			case "B_ID":
				return new B();
			default:
				throw new InvalidOperationException("Invalid factory identifier");
		}
	}
}

class ReflectionFactory
{
	private readonly static Dictionary<string, Type> ReturnableTypes;

	static ReflectionFactory()
	{
		ReturnableTypes = GetReturnableTypes();
	}

	private static Dictionary<string, Type> GetReturnableTypes()
	{
		// get a list of the types that the factory can return
		// criteria for matching types:
		// - must have a parameterless constructor
		// - must have correct factory attribute, with non-null, non-empty value
		// - must have correct BaseType (if OutputType is not generic)
		// - must have matching generic BaseType (if OutputType is generic)

		Dictionary<string, Type> returnableTypes = new Dictionary<string, Type>();

		Type outputType = typeof(IDoSomething);
		Type factoryLabelType = typeof(FactoryAttribute);
		foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
		{
			string assemblyName = assembly.GetName().Name;
			if (!assemblyName.StartsWith("System") &&
				assemblyName != "mscorlib" &&
				!assemblyName.StartsWith("Microsoft"))
			{
				foreach (Type type in assembly.GetTypes())
				{
					if (type.GetCustomAttributes(factoryLabelType, false).Length > 0)
					{
						foreach (object label in ((FactoryAttribute)type.GetCustomAttributes(factoryLabelType, true)[0]).Labels)
						{
							if (label != null && label.GetType() == typeof(string))
							{
								if (outputType.IsAssignableFrom(type))
								{
									returnableTypes.Add((string)label, type);
								}
							}
						}
					}
				}
			}
		}

		return returnableTypes;
	}

	public static IDoSomething Create(string id)
	{
		if (ReturnableTypes.ContainsKey(id))
		{
			return (IDoSomething)Activator.CreateInstance(ReturnableTypes[id]);
		}
		else
		{
			throw new Exception("Invalid factory identifier");
		}
	}
}

[Factory("A_ID")]
class A : IDoSomething
{
	public void DoIt()
	{
		Console.WriteLine("Letter A");
	}
}

[Factory("B_ID")]
class B : IDoSomething
{
	public void DoIt()
	{
		Console.WriteLine("Letter B");
	}
}

public interface IDoSomething
{
	void DoIt();
}

#region magic factory code
/// <summary>
/// Attribute class for decorating classes to use with the generic Factory
/// </summary>
public sealed class FactoryAttribute : Attribute
{
	public IEnumerable<object> Labels { get; private set; }
	public FactoryAttribute(params object[] labels)
	{
		if (labels == null)
		{
			throw new ArgumentNullException("labels cannot be null");
		}
		Labels = labels;
	}
}

/// <summary>
/// Custom exception class for factory creation errors
/// </summary>
public class FactoryCreationException : Exception
{
	public FactoryCreationException()
		: base("Factory failed to create object")
	{
	}
}

/// <summary>
/// Generic Factory class.  Classes must have a parameterless constructor for use with this class.  Decorate classes with 
/// <c>FactoryAttribute</c> labels to match identifiers
/// </summary>
/// <typeparam name="TInput">Input identifier, matches FactoryAttribute labels</typeparam>
/// <typeparam name="TOutput">Output base class / interface</typeparam>
public class Factory<TInput, TOutput>
	where TOutput : class
{
	private static readonly Dictionary<TInput, int> JumpTable;
	private static readonly Func<TInput, TOutput> Creator;

	static Factory()
	{
		JumpTable = new Dictionary<TInput, int>();
		Dictionary<TInput, Type> returnableTypes = GetReturnableTypes();
		int index = 0;
		foreach (KeyValuePair<TInput, Type> kvp in returnableTypes)
		{
			JumpTable.Add(kvp.Key, index++);
		}
		Creator = CreateDelegate(returnableTypes);
	}

	/// <summary>
	/// Creates a TOutput instance based on the label
	/// </summary>
	/// <param name="label">Identifier label to create</param>
	/// <returns></returns>
	public static TOutput Create(TInput label)
	{
		return Creator(label);
	}

	/// <summary>
	/// Creates a TOutput instance based on the label
	/// </summary>
	/// <param name="label">Identifier label to create</param>
	/// <param name="defaultOutput">default object to return if creation fails</param>
	/// <returns></returns>
	public static TOutput Create(TInput label, TOutput defaultOutput)
	{
		try
		{
			return Create(label);
		}
		catch (FactoryCreationException)
		{
			return defaultOutput;
		}
	}

	private static Dictionary<TInput, Type> GetReturnableTypes()
	{
		// get a list of the types that the factory can return
		// criteria for matching types:
		// - must have a parameterless constructor
		// - must have correct factory attribute, with non-null, non-empty value
		// - must have correct BaseType (if OutputType is not generic)
		// - must have matching generic BaseType (if OutputType is generic)

		Dictionary<TInput, Type> returnableTypes = new Dictionary<TInput, Type>();

		Type outputType = typeof(TOutput);
		Type factoryLabelType = typeof(FactoryAttribute);
		foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
		{
			string assemblyName = assembly.GetName().Name;
			if (!assemblyName.StartsWith("System") &&
				assemblyName != "mscorlib" &&
				!assemblyName.StartsWith("Microsoft"))
			{
				foreach (Type type in assembly.GetTypes())
				{
					if (type.GetCustomAttributes(factoryLabelType, false).Length > 0)
					{
						foreach (object label in ((FactoryAttribute)type.GetCustomAttributes(factoryLabelType, true)[0]).Labels)
						{
							if (label != null && label.GetType() == typeof(TInput))
							{
								if (outputType.IsAssignableFrom(type))
								{
									returnableTypes.Add((TInput)label, type);
								}
							}
						}
					}
				}
			}
		}

		return returnableTypes;
	}

	private static Func<TInput, TOutput> CreateDelegate(Dictionary<TInput, Type> returnableTypes)
	{
		// get FieldInfo reference to the jump table dictionary
		FieldInfo jumpTableFieldInfo = typeof(Factory<TInput, TOutput>).GetField("JumpTable", BindingFlags.Static | BindingFlags.NonPublic);
		if (jumpTableFieldInfo == null)
		{
			throw new InvalidOperationException("Unable to get jump table field");
		}

		// set up the IL Generator
		DynamicMethod dynamicMethod = new DynamicMethod(
			"Magic",										// name of dynamic method
			typeof(TOutput),								// return type
			new[] { typeof(TInput) },						// arguments
			typeof(Factory<TInput, TOutput>),				// owner class
			true);
		ILGenerator gen = dynamicMethod.GetILGenerator();

		// define labels (marked later as IL is emitted)
		Label creationFailedLabel = gen.DefineLabel();
		Label[] jumpTableLabels = new Label[JumpTable.Count];
		for (int i = 0; i < JumpTable.Count; i++)
		{
			jumpTableLabels[i] = gen.DefineLabel();
		}

		// declare local variables
		gen.DeclareLocal(typeof(TOutput));
		gen.DeclareLocal(typeof(TInput));
		LocalBuilder intLocalBuilder = gen.DeclareLocal(typeof(int));

		// emit MSIL instructions to the dynamic method
		gen.Emit(OpCodes.Ldarg_0);
		gen.Emit(OpCodes.Stloc_1);
		gen.Emit(OpCodes.Volatile);
		gen.Emit(OpCodes.Ldsfld, jumpTableFieldInfo);
		gen.Emit(OpCodes.Ldloc_1);
		gen.Emit(OpCodes.Ldloca_S, intLocalBuilder);
		gen.Emit(OpCodes.Call, typeof(Dictionary<TInput, int>).GetMethod("TryGetValue"));
		gen.Emit(OpCodes.Brfalse, creationFailedLabel);
		gen.Emit(OpCodes.Ldloc_2);
		// execute the MSIL switch statement, effectively giving us O(1) access to each case
		gen.Emit(OpCodes.Switch, jumpTableLabels);

		// set up the jump table
		foreach (KeyValuePair<TInput, int> kvp in JumpTable)
		{
			gen.MarkLabel(jumpTableLabels[kvp.Value]);
			// create the type to return
			gen.Emit(OpCodes.Newobj, returnableTypes[kvp.Key].GetConstructor(Type.EmptyTypes));
			gen.Emit(OpCodes.Ret);
		}

		// CREATION FAILED label
		gen.MarkLabel(creationFailedLabel);
		gen.Emit(OpCodes.Newobj, typeof(FactoryCreationException).GetConstructor(Type.EmptyTypes));
		gen.Emit(OpCodes.Throw);

		// create a delegate so we can later invoke the dynamically created method
		return (Func<TInput, TOutput>)dynamicMethod.CreateDelegate(typeof(Func<TInput, TOutput>));
	}
}
#endregion

 

Moq'ing successive calls with the same arguments

by abutler 30. March 2011 11:30

I like Moq.  For me it has made unit testing almost enjoyable, similar to how jQuery makes writing javascript more bearable.

 

Today I ran into an issue.  I'm mocking System.Data.IDataReader (I'm old school okay, but I'm writing unit tests, so give me a break).  So in my code, I call the Read() method of IDataReader until it returns false.

 

while (reader.Read())
{
	// old man code here
}

 

Moq is great when you setup calls to a method that are somewhat unique.  But in this case, each successive call has the same arguments (no argument).  So how can I get Read() to return true the first time, then false on any call after that?  Well it's probably in the Moq documentation somewhere, but forget that.  Here's my solution:

 

var readerMock = new Mock<System.Data.IDataReader>();
int row = 0;
readerMock.Setup(x => x.Read()).Returns(row++ == 0);

 

Except that doesn't seem to work quite right, since it evaluates upon setup, not on invocation.  Or something.  This seems to work:

 

var readerMock = new Mock<System.Data.IDataReader>();
int row = 0;
readerMock.Setup(x => x.Read()).Returns(() => row++ == 0);

Now it gets evaluated when it is invoked I think.  It works at any rate.  Plus the inclusion of a lambda expression gives the added benefit of making it appear that I know what I'm doing.

 

SQL Indexing in a Nutshell

by abutler 29. March 2011 10:55

 

Don't do it like this.  That is all

 

Changing fields to properties in a Serializable class

by abutler 28. March 2011 15:47

Recently, I began preparing our code for code analysis using FxCop.  In beginning the project, I chose to enforce rule CA1051, part of the Microsoft Minimum Recommended Rules ruleset.  Seems pretty straightforward right?  I'll just have to change some fields to properties, maybe deal with some scoping issues, refactor some code, etc.

 

One of the problems I ran up against while enforcing this rule was in dealing with some of our serializable classes.  Say you have a class like this one:

 

[Serializable]
public class FieldsAreAwesome
{
	public int WhyNot;
}

 

This presents a bit of a problem, as changing the class to 

 

[Serializable]
public class FieldsAreAwesome
{
	public int WhyNot { get; set; }
}

 

will break serialization (properties are not serialized).  So there are a few options:

 

  1. Change the field scope to private, add a property to encapsulate then change all dependent code
  2. Implement custom serialization
  3. Just break it and hope the blame goes to someone else

 

#2 is not really a possibility, since the properties would have to have a different name and the amount of dependent code to be changed is not trivial in our codebase.

 

#1 turns out to be the only real option.  To do custom serialization, you have to implement ISerializable, like this:

 

[Serializable]
public class FieldsAreAwesome : ISerializable
{
	public int WhyNot { get; set; }

	#region ISerializable Members

	private FieldsAreAwesome(SerializationInfo info, StreamingContext context)
	{
		WhyNot = info.GetInt32("WhyNot");
	}

	public void GetObjectData(SerializationInfo info, StreamingContext context)
	{
		info.AddValue("WhyNot", WhyNot);
	}

	#endregion
}

 

The new constructor is required for deserialization, your code will fail at runtime if you don't have a constructor with the right arguments.

 

Say we had a serialized object from this class that was persisted somewhere.  This object is then deserialized using the new class above.  Since the names match, it will work.  Subsequent serializations / deserializations will also work using the new class.

 

Did I test this?  Yes.  Is there a better way of doing this?  Probably.  Will something break in production as a result of this? I certainly hope not.

 

Update:

Here's a better way to write the serialization constructor:

private FieldsAreAwesome(SerializationInfo info, StreamingContext context)
{
	foreach (SerializationEntry entry in info)
	{
		switch (entry.Name)
		{
			case "WhyNot":
				WhyNot = (int)entry.Value;
				break;
		}
	}
}
One thing to keep in mind is that once you commit to doing serialization yourself, you have to account for pretty much every scenario.  Checking for existing fields in the serialization info BEFORE trying to deserialize that field is a good idea.  I found this out the hard way.

About the authors

We like to rock ICS Bank 2

Month List