Friday, June 22, 2012

List all values of an enumeration

I'm probably late to the party on this one, but I recently discovered a cool, handy little static method tucked away in the Enum class: GetValues. It simply returns all the values of an enum type. This enables nifty things like:
public enum TestEnum
{
    Value1,
    Value2,
    Value3,
    Value4
};

public void ShowEnumValues()
{
    Enum.GetValues(typeof (TestEnum))
        .Cast<TestEnum>()
        .ToList()
        .ForEach(e => Console.WriteLine(e));
}
With this, any changes to TestEnum automatically get picked up at run-time without any additional changes to the rest of the code.

Last year, I wrote about using a dictionary to facilitate converting between an enum and human readable text. To adapt the code presented then to the above example, the following will convert all values in the enum to human readable text.
private IDictionary<TestEnum, string> enumToString =
    new Dictionary<TestEnum, string>
        {
            {TestEnum.Value1, "Value one"},
            {TestEnum.Value2, "Value two"},
            {TestEnum.Value3, "Value three"},
            {TestEnum.Value4, "Value four"}
        };

public void ShowEnumStrings()
{
    Enum.GetValues(typeof(TestEnum))
        .Cast<TestEnum>()
        .ToList()
        .ForEach(e => Console.WriteLine(enumToString[e]));
}

In the previous article, I lamented the fact that this C# solution, unlike the Pascal variant, does not provide a reliable means to check that all the values of the enumeration have a corresponding entry in the dictionary. Because of strong typing with generics, I know I can't have any thing that's not part of the enumeration in the dictionary, but I can't know I have all the values of the enumeration in the dictionary. In other words, I know I can't have any invalid values, but I can't know I have all the values.

Until I found this method. Now I can at least write an easy test case for this. While it's not quite as good as a compile time check, it does give an early, reliable means of being alerted to the problem.
[TestMethod]
public void EnsureAllEnumValuesAreInDictionary()
{
    Assert.IsTrue(
        Enum.GetValues(typeof(TestEnum))
            .Cast<TestEnum>()
            .All(type => EnumToString.ContainsKey(type)),
        "Enum value missing from enumToString dictionary");
}

Since variables of this type typically do not change from instance to instance, they can be made static so they're only instantiated once. And since many times they are only used inside a single class, they can be made private. In these cases having a unit test might be problematic, not being able to test a private field. To solve this, code similar to the above test can be put in a static constructor, throwing an exception if there's a mismatch.
private static readonly IDictionary<TestEnum, string> EnumToString =
    new Dictionary<TestEnum, string>
        {
            {TestEnum.Value1, "Value one"},
            {TestEnum.Value2, "Value two"},
            {TestEnum.Value3, "Value three"},
            {TestEnum.Value4, "Value four"}
        };

static UnitTest1()
{
    if (!Enum.GetValues(typeof (TestEnum))
             .Cast<TestEnum>()
             .All(type => EnumToString.ContainsKey(type)))
        throw new InvalidOperationException(
            "Enum value missing from enumToString dictionary");
}

Finally, if this needs to be done much, making a generic helper function will clean-up code, hiding all the casting and repetition of the type.
private static IEnumerable<T> GetEnumValues<T>()
{
    return Enum.GetValues(typeof (T)).Cast<T>();
}

[TestMethod]
public void EnsureAllEnumValuesAreInDictionary1()
{
    Assert.IsTrue(
        GetEnumValues().All(type => EnumToString.ContainsKey(type)),
        "Enum value missing from enumToString dictionary");
}

All in all, I'm pleased with finding this little nugget.

A complete VS2008 solution containing the code examples above is available on github.

Hope this helps someone else.

Monday, June 4, 2012

Functional FizzBuzz in C#

Back when Jeff Atwood first wrote about FizzBuzz, I implemented it a number of different ways in Delphi. It was an interesting exercise; I think I came up with around five different ways to implement it. I also did some performance testing and was surprised by the results. Perhaps someday I'll try to find that code and publish it. Over the years since, I've used it, or variations, in interviews and have been surprised at how many applicants it weeded out.

Recently I ran across an article listing several ways to do it in various functional languages and wondered how functional I could code it in C#. So, I fired up Visual Studio and created a new console project. I didn't think my first attempt was too bad.
namespace FunctionalFizzBuzz
{
  class Program
  {
    static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return showFizz && showBuzz
        ? "FizzBuzz"
        : showFizz
          ? "Fizz"
          : showBuzz
            ? "Buzz"
            : val.ToString(CultureInfo.InvariantCulture);
    }

    static string GenerateFizzBuzz(int start, int end)
    {
      return Enumerable
        .Range(start, end)
        .Aggregate(new StringBuilder(), (seed, val) =>
          {
            seed.AppendLine(FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
            return seed;
          })
        .ToString();
    }

    static void Main(string[] args)
    {
      Console.WriteLine(GenerateFizzBuzz(1, 100));
    }
  }
}

However, there were a couple things I didn't like about it. First, returning the whole result as a string seemed a bit overkill and intuitively not too memory friendly. For purposes of displaying 100 lines, it's not too bad, but for a more general use case, it's not good for composition. Second, the use of Aggregate bothered me a bit. How it works is not obvious to most people when first seeing it; it's use is a bit obtuse. And concatenating a bunch of strings just felt wrong.

So, I replaced the string result with an IEnumerable. This allowed changes which I think expresses the intent better. First, the Aggregate could be be changed to a Select, clarifying the GenerateFizzBuzz method. Second, the call to Console.WriteLine to generate each output line could be passed as a parameter to an iterator function. This is an example of how the new method makes it easier to use the output for different things. Another example is to count how many "Fizz" lines there are.

static IEnumerable GenerateFizzBuzz(int start, int end)
{
  return Enumerable
    .Range(start, end-start+1)
    .Select(val => FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
}

static void Main(string[] args)
{
  var result = GenerateFizzBuzz(1, 100).ToList();
  result.ForEach(Console.WriteLine);
  Console.WriteLine("Number of Fizzes: {0}", results.Count(l => l == "Fizz"));
}

With the GenerateFizzBuzz method cleaned up some, my attention turned to the FizzBuzzResult method. I wasn't terribly happy with the multiple nested conditional statement. While functional, it seemed more computational than declarative to me. What it did was a bit opaque. I like the parameter pattern matching available in the more functional languages and wondered how I could do something similar. I couldn't think of a way to let the compiler do it and regular expressions (the only pattern matching I can think of in the .Net libraries) only works on strings. However, it seemed pretty straight forward using a data structure.

I created a dictionary with a boolean key and dictionary value. The nested dictionary also had a boolean key but with a string value. I initialized these with the four possible values. The case which should return the numeric value was set to null. Then then the result was simply the lookup value of the dictionaries unless it returned null, in which case it was the passed in value, converted to a string.

private static readonly Dictionary<bool, Dictionary<bool, string>>
  FizzBuzzMap =
    new Dictionary<bool, Dictionary<bool, string>>
      {
        {true, new Dictionary<bool, string> {{true, "FizzBuzz"}, {false, "Fizz"}}},
        {false, new Dictionary<bool, string> {{true, "Buzz"}, {false, null}}}
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[showFizz][showBuzz] ?? val.ToString(CultureInfo.InvariantCulture);
}

I liked the way FizzBuzzResult looked, but the initialization code for the dictionaries was a bit ugly to my eye. I tried changing it to a single dictionary containing an array of booleans as the key.

private static readonly Dictionary<bool[], string>
  FizzBuzzMap =
    new Dictionary<bool[], string>
      {
        {new[] {true, true}, "FizzBuzz"},
        {new[] {true, false}, "Fizz"},
        {new[] {false, true}, "Buzz"},
        {new[] {false, false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new [] {showFizz, showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}

Ah, this looked much nicer. But... it raised a key not found exception. Oops. Fail. I hypothesized the key comparison during lookup looked at the arrays as objects, rather than the values they contained, and so raised the exception. I quickly wrote a comparison class for the dictionary and passed in an instance of it.

internal class BoolArrayComparer : IEqualityComparer
{
  public bool Equals(bool[] x, bool[] y)
  {
    if (x.Length != y.Length)
      return false;
    return !x.Where((t, i) => t != y[i]).Any();
  }

  public int GetHashCode(bool[] obj)
  {
    return obj.Aggregate(0, (seed, val) => seed + val.GetHashCode());
  }
}

Sure enough, it now worked properly. So the initialization looked pretty, but at the expense of having to have this extra, ugly class floating around spoiling things. Reflecting on the prior solution with the arrays, I realized structures have slightly different semantics and might work better with comparison. I changed the boolean array to a two member structure.

internal struct FizzBuzzKey
{
  internal bool showFizz;
  internal bool showBuzz;
};

private static readonly Dictionary
  FizzBuzzMap =
    new Dictionary
      {
        {new FizzBuzzKey {showFizz = true, showBuzz = true}, "FizzBuzz"},
        {new FizzBuzzKey {showFizz = true, showBuzz = false}, "Fizz"},
        {new FizzBuzzKey {showFizz = false, showBuzz = true}, "Buzz"},
        {new FizzBuzzKey {showFizz = false, showBuzz = false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new FizzBuzzKey {showFizz = showFizz, showBuzz = showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}

And this worked without requiring a Comparer class. But it's quite a bit more verbose than the array notation; I really liked the succinctness of the array notation. Then I remembered structs can have constructors. I added one and this helped cut down the verbosity quite a bit.

So, in the end I finished this little exercise with the following.

namespace FunctionalFizzBuzz
{
  internal class Program
  {
    internal struct FizzBuzzKey
    {
      internal FizzBuzzKey(bool showF, bool showB)
      {
        showFizz = showF;
        showBuzz = showB;
      }

      internal bool showFizz;
      internal bool showBuzz;
    };

    private static readonly Dictionary
      FizzBuzzMap =
        new Dictionary
          {
            {new FizzBuzzKey (true, true), "FizzBuzz"},
            {new FizzBuzzKey (true, false), "Fizz"},
            {new FizzBuzzKey (false, true), "Buzz"},
            {new FizzBuzzKey (false, false), null},
          };

    static void Main(string[] args)
    {
      var results = Enumerable
        .Range(90, 11)
        .Select(val => FizzBuzzResult(val%3 == 0, val%5 == 0, val))
        .ToList();
      results.ForEach(Console.WriteLine);
      Console.WriteLine("Number of Fizzes: {0}", results.Count(l => l == "Fizz"));
    }

    private static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return FizzBuzzMap[new FizzBuzzKey(showFizz, showBuzz)] ?? val.ToString(CultureInfo.InvariantCulture);
    }
  }
}

Final thoughts

One solution I considered during this process was to map the four values of booleans to integers and do a lookup after a conversion. Intuitively, I didn't like the approach because it added an extra level of abstraction. Levels of abstraction can be good if they clarify. However, in this case, I thought it would simply obfuscate. In spite of this, out of desire to be complete, I threw this implementation together too.

private static readonly Dictionary
  FizzBuzzMap =
    new Dictionary()
      {
        {3 /* true, true */, "FizzBuzz"},
        {2 /* true, false */, "Fizz"},
        {1 /* false, true */, "Buzz"},
        {0 /* false, false */, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[(val%3 == 0 ? 1 : 0) + (val%5 == 0 ? 1 : 0)] ?? val.ToString(CultureInfo.InvariantCulture);
}

But it didn't work. It emitted "Buzz" in places it should have output "Fizz." But not all the time. It took me a minute or two to find it.

Can you spot the error?


The fact that 1) this was the first bug I'd produced during this exercise, 2) it wasn't immediately obvious what the problem was and 3) the need for the comments in the setup, all confirmed my suspicion this is not a good solution.

Two other things I vacillated over was whether FizzBuzzResult needed to be a separate routine and, if so, what its parameters should be. At times I'd roll it into the main routine and other times I'd pass in just the numeric value and yet other times I'd pass in the three parameters as shown. I concluded that a toy exercise like this is too small to really have a clear winner in this debate. Additional use cases provided by a larger application would probably make one of these various options a clear winner.

After going through this process, I did a web search on "C# functional FizzBuzz" and found a number of solutions including this interesting take.

Monday, April 2, 2012

There and back again, again: Any resource's tale

Or, how to generically set and restore state when an exception is raised

I've written twice before (here and here) about making cursor changes more robust with the using statement in C#. These allow states to be reset to correct values regardless of whether or not an exception is raised during some processing. As promised at the end of the last article, today I explain how to use lambdas to easily protect any type of "resource" without having to create a new class or sprinkle your code with try/finally blocks.

To set things up and provide a bit of context, the other day in a code review, I found this:

someFlag = true;
someStartStateMethod();
// Do some work
someResetStateMethod();
someFlag = false;

Over the years, I've seen this pattern repeated, in different domains and different languages and not necessarily limited to setting a flag. Whenever I do, I ask "if an exception happens anywhere in 'do some work,' should the state be reset?" I won't say the answer should always be "yes," but I've not yet found a "no." And this case was no exception.

Since some of the places this was done was nested, I wanted a way to clean all this up that didn't involve adding try/finally blocks. Each try/finally would add another level of indentation; it would get pretty deep pretty fast. Also, it would clutter up the code with noise that didn't really have anything to do with the work needing to be done. In other words, I didn't want this:

someFlag = true;
try
{
   someStartStateMethod();
   try
   {
     // Do some work
   }
   finally
   {
      someResetStateMethod();
   }
}
finally
{
   someFlag = false;
}

In my last article, I separated the code actually handling the protection from the code controlling the invocation of that protection by using inheritance. I created a base abstract class to handle the general IDisposable pattern and descendent classes to handle the actual protection. In that article, I showed a class to handle changing a cursor and then changing it back to the current value.

I quickly realized this code was simply another example of that pattern. I could do the same thing as earlier and put the someStartStateMethod() and someResetStateMethod() in a descendant class. If I followed that pattern, the code under review could be something more along the lines of:

using(new ChangeSomeFlag())
using(new ChangeSomeStateMethod())
{
   // Do some work
}

This is somewhat better.

However, in this case, creating a new class for each thing needing protection didn't seem too appealing. There would be a lot of small special purpose classes, some of which might only be used once. It seemed like a sledgehammer to drive a brad. For this code, I wanted to emphasize composition over inheritance.

Enter lambdas. Because lambdas allow you to treat code as data, they allow easy composition. The LINQ and Rx libraries are great examples. They provide many generic methods (e.g. Where, Select, Any) that have the ability to compose in functionality through the use of lambdas to work on specific types for specialized purposes.

In this particular case, lambdas can be used to contain the code that handles the protection and passed to a class whose sole job is to handle the invocation of that code at the appropriate time. Rewriting the previous example with a new, as yet undefined ResourceProtector class, its use looks like:

using(new ResourceProtector(() => someFlag = true, () => someFlag = false))
using(new ResourceProtector(() => someSetStateMethod(), () => someResetStateMethod()))
{
   // Do some work
}

In this code, two expressions are passed to the constructor of the ResourceProtector class that handle the saving and restoring of state. Here is a single class that can be reused over and over in different situations to protect different types of resources. I think this is a beautiful example of the single responsibility principle combined with the power of lambda expressions to handle composition.

public class ResourceProtector : IDisposable
{
   private bool Disposed { get; set; }
   private Action EndProtection { get; set; }

   public ResourceProtector(Action startProtection, Action endProtection)
   {
      Disposed = false;
      EndProtection = endProtection;
      startProtection();
   }

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

   private void DisposeInt()
   {
      if (Disposed)
         return;

      EndProtection();
      Disposed = true;
   }

   ~ResourceProtector()
   {
      DisposeInt();
   }
}

If you have any questions, suggestions or comments, please feel free to leave them below. Until next time, subscribe to the Twitter feed to get notified of future articles and hear about other development related things.

Wednesday, March 21, 2012

7 ways to remove duplicate strings from a list (with timing results)

Recently there was a question on CodeProject about the fastest way to remove duplicate strings from a List. There were a bunch of alternative solutions presented, but no comparison to see what was faster. This post will show each solution and time them in a standard way to determine which actually answers the question.

About the test

Test setup creates a list of 1,000 random strings all 50 characters long. This is the expected result. It then creates duplicates for every other item and then for every 5th item. A list containing duplicates is created from the expected results and the duplicates. Note that for the even 5th items, there are actually two duplicates in the final list.

The core test method takes the list of duplicates, sets up a stopwatch and then calls the method to remove duplicates 1,000 times, each time passing in a new copy of the duplicate list. Since one of the methods under test changes the input list, this causes each iteration to work on the same, pristine input list. The elapsed time from the stopwatch is output and assertions are in place to make sure the method under test does what's expected.

About the methods under test

I've taken the code presented in the original thread and made slight modifications to make them all conform to the same interface. Some of them were code snippets or descriptions so I made my best guess as to the authors' intent.

1. The original poster's solution

public static IList LoadUniqueList1(List doubledList)
{
   var uniqueList = new List();
   foreach (var item in doubledList)
   {
      var x = true;
      foreach (var compare in uniqueList)
      {
         if (item == compare)
         {
            x = false;
         }
         if (!x) break;
      }
      if (x)
         uniqueList.Add(item);
   }
   return uniqueList;
}

2. Same as above, except substituting Contains for the second loop

public static IList LoadUniqueList2(List doubledList)
{
   var uniqueList = new List();
   foreach (var item in doubledList)
   {
      if (!uniqueList.Contains(item))
         uniqueList.Add(item);
   }
   return uniqueList;
}

3. Using a SortedList

public static IList LoadUniqueList3(List doubledList)
{
   var uniqueList = new SortedList();
   foreach (var item in doubledList)
   {
      if (!uniqueList.ContainsKey(item))
         uniqueList.Add(item, item);
   }
   return uniqueList.Values;
}

4. Using a HashSet

public static IList LoadUniqueList4(List doubledList)
{
   return new HashSet(doubledList).ToList();
}

5. Using LINQ Distinct

public static IList LoadUniqueList5(List doubledList)
{
   return doubledList.Distinct().ToList();
}

6. Using LINQ double iteration

public static IList LoadUniqueList6(List doubledList)
{
   var uniqueList = new List();
   uniqueList.Add(
      (from itm in uniqueList
      from compareItem in doubledList
      where itm == compareItem
      select compareItem).ToString());
   return uniqueList;
}

7. Sort and then build filtered list

public static IList LoadUniqueList7(List doubledList)
{
   var uniqueList = new List();
   doubledList.Sort();
   string lastEntry = string.Empty;
   foreach (string str in doubledList)
   {
      if (str != lastEntry)
      {
         uniqueList.Add(str);
         lastEntry = str;
      }
   }
   return uniqueList;
}

Timing results

The table below shows the elapsed time results for three test runs and the average elapsed time. The last column is how the strategy performed.

Before looking at the results, ask yourself "Which are the top two best performers?"


Comments about either the test methodology or results can be left below.

Test project available here.

Monday, March 12, 2012

There and back again, again: Several resource's tale

Or, how to safely change a cursor or other resource

In a previous article, I presented a simple class that utilized the IDisposable pattern to set the cursor to a specific value and then automatically reset it to the initial state when some work was accomplished. This simple class had two limitations: it only worked with WPF and it only worked on cursors.

To overcome these limitations, I refactored this to be more general. I changed the context to a generic type and added an abstract RestoreState method that's called when the class is either destroyed (preferred) or the finalizer is called. This allows all the basic plumbing regarding the IDisposable pattern to be contained in one class.

using System;

namespace ResourceProtection
{
    public abstract class ResourceChangeHandler : IDisposable
    {
        protected TContext Context { get; set; }
        private bool Disposed { get; set; }

        protected ResourceChangeHandler(TContext context)
        {
            Disposed = false;
            Context = context;
        }

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

        protected abstract void RestoreState(TContext context);

        private void DisposeInt()
        {
            if (Disposed)
                return;

            RestoreState();
            Disposed = true;
        }

        ~ResourceChangeHandler()
        {
            DisposeInt();
        }
    }
}

The beauty of this is it can be used as the base class for specific needs. The function of actually changing a resource is split out from the framework needed to manage the change. Here are three examples: one each for a WPF cursor changer, a WinForms cursor changer and a TreeView BeginUpdate/EndUpdate handler.

How to change a WPF cursor

public class WpfChangeCursor : ResourceChangeHandler{
    private Cursor OriginalCursor { get; set; }

    public WpfChangeCursor(FrameworkElement element, Cursor newCursor)
            : base(element)
    {
        OriginalCursor = Context.Cursor;
        Context.Cursor = newCursor;
    }

    protected override void RestoreState()
    {
        Context.Cursor = OriginalCursor;
    }
}

To use this, instantiate an instance of WpfChangeCursor in a using block, passing in the element who's cursor should be changed and the new value for the cursor. In this case, the context for the base class is the element containing the cursor to be changed. The descendant class has the responsibility to remember the current value and changing the cursor.

How to change a WinForm cursor

public class WinFormChangeCursor : ResourceChangeHandler{
    private Cursor OriginalCursor { get; set; }

    public WinFormChangeCursor(Cursor newCursor)
            : base(Cusor.Current)
    {
        Cursor.Current = newCursor;
    }

    protected override void RestoreState()
    {
        Cursor.Current = Context;
    }
}

This class is used by instantiating an instance of WinFormChangeCursor in a using block with the new value of the cursor passed to it. This is a little different from the WPF version since there is only one cursor for the application, rather than for each element. In this case, the context passed to the base is the current cursor value which is then used by RestoreState to put things back.

How to call BeginUpdate and EndUpdate safely

public class TreeViewUpdate : ResourceChangeHandler{
    public TreeViewUpdate(TreeView treeview)
            : base(treeview)
    {
        Context.BeginUpdate();
    }

    protected override void RestoreState()
    {
        Context.EndUpdate();
    }
}

And finally, here's a class to make sure EndUpdate is called for every BeginUpate on a TreeView. Like the WPF cursor changer above, the control is passed in as the context for the ancestor class. BeginUpdate is then called on the context. When the using block this class is controlled by finishes, the EndUpdate in RestoreState is called, again on the same context as the BeginUpdate.

This technique provides for a level of separation between the framework needed to safely do and undo things from the actual work of doing and undoing them. It works well for certain classes of problems, specifically fixed things that happen over and over again. The examples above of doing repetitive things on framework level items are good examples.

Sometimes though, one wants this type of functionality without the overhead of creating a new class each time. In the next article, I'll present a method of composing this type of behavior in a more adhoc manner.

Until then, subscribe to the Twitter feed to get notified of future articles and hear about other development related things. And if you have any questions, suggestions or comments, please feel free to leave them below.

Tuesday, September 27, 2011

How to fix Visual Studio C++ Warning: LINK4075

At the beginning of last week's sprint, I picked up a task to reduce our warning count. One of the issues that I scratched my head over a couple minutes was a bunch of warnings with the text warning LNK4075: ignoring '/EDITANDCONTINUE' due to '/SomeOtherSetting' specification. As indicated by the LNK identifier, I knew the linker emitted this warning. However, in my perusal of the linker options, I couldn't find where the EDITANDCONTINUE setting existed. I even glanced through the other property pages looking for it.

Per my wont, I searched the web and eventually found it based on some oblique references on a StackOverflow question. The reason I had trouble finding it? It's a compiler option. And it's not called EDITANDCONTINUE.

This is controlled by the Debug Information Format setting on the C/C++ General page. If the option is Program Database and Edit and Continue, a.k.a. /ZI, then the output obj files apparently have a flag embedded in them that is incompatible with certain settings in the linker. Hence, the linker emits the warnings when it hits these conditions. It would have been nice for the message to have contained the /ZI option (which is what's used in the compiler) rather then than the EDITANDCONTINUE pseudo-option which isn't used anywhere, as near as I can tell.

To fix this warning, either change the linker options that are incompatible with the /ZI option or change the compiler option to something other than /ZI, such as /Zi. As of the time of this writing, the linker options incompatible with EDITANDCONTINUE include setting optimization to /OPT:REF or /OPT:ICF, turning off incremental compilation or setting one of /ORDER, /RELEASE or /FORCE. (These are from this MSDN page.)

Hope this helps someone.

Friday, September 23, 2011

Sharing folders with Windows 8 between VirtualBox machines

Currently Windows 8 runs just fine inside a VirtualBox machine. However, guest additions, the tools to enable certain useful features of VirutalBox, do not yet work with Windows 8. Today I wanted to use some Visual Studio projects from an existing Windows XP virtual machine in my new Windows 8 machine. The obvious first choice was to simply use a shared folder on the host in both virtual machines. However, this requires the guest additions, so I went looking for a work around.

What I found to work was a second virtual hard drive. In VirtualBox, on my primary development machine, I created a new hard drive on the existing IDE controller. I then started the machine and went into Windows' device manager. The disk manager started the new disk wizard. After initialization, I created and formatted an NTFS partition. I then copied the files I wanted to work with to this new disk. Finally I shutdown this machine.

Next, in VirturalBox, I added the same, new hard drive image as a second drive on the Window 8 box's SATA controller. (If you add the drive to the IDE controller, Windows 8 will try to boot to it first and fail with a bad image error.) When I booted Windows 8 and went into Explorer, the second drive showed up with all the data I'd copied to it.

That's it, pretty simple and straight forward, but not the obvious (to me) first solution.

Warning: I don't know what would happen if both virtual machines are run at the same time. I suspect (and hope) the second one started would get some sort of sharing violation and not allow the disk to be mounted. I can't imagine VirtualBox is smart enough to allow two machines to attach to the same vdi file at the same time without corrupting the data. However, it seems to work just fine as long as there is only one machine using the file at any given point of time.

Hope this helps someone.