14 August 2010 by Stuart Cam
Thycotic have put up a Code Challenge.
Below is my heavily LINQ-oriented solution:
public interface IConverter
{
string Convert(int number);
int Convert(string number);
string ConvertUsing(IConverter convertor, string number);
}
public abstract class ConverterBase : IConverter
{
protected abstract string Chars { get; }
public string Convert(int number)
{
return this.Encode(number)
.Aggregate(string.Empty, (s, c) => s + c);
}
public int Convert(string number)
{
return number.Reverse()
.Select((c, i) => Chars.IndexOf(c) * (int)Math.Pow(this.Chars.Length, i))
.Sum();
}
public string ConvertUsing(IConverter convertor, string number)
{
return convertor.Convert(this.Convert(number));
}
private IEnumerable<char> Encode(int number)
{
var remainder = number % this.Chars.Length;
if (number - remainder > 0)
{
foreach (var power in this.Encode((number - remainder) / this.Chars.Length))
{
yield return power;
}
}
yield return this.Chars[remainder];
}
}
public class Converter : ConverterBase
{
protected override string Chars
{
get
{
return "0123456789xyz";
}
}
}
public class HexConverter : ConverterBase
{
protected override string Chars
{
get
{
return "0123456789abcdef";
}
}
}
public class BinaryConverter : ConverterBase
{
protected override string Chars
{
get
{
return "01";
}
}
}
public class OctalConverter : ConverterBase
{
protected override string Chars
{
get
{
return "01234567";
}
}
}
Note: The code doesn't handle negative inputs or exceptions.
14 May 2009 by Stuart Cam
I just stumbled across a problem in my integration testing around a particular scenario.
The problem occurs when attempting to create a mock instance for a class that has a generic method with a generic constraint - either at the class or method level.
Consider the following code:
public interface IFoo<T> where T : IBar
{
T Get();
}
We have added a constraint to the interface IFoo such that T must implement IBar. So far so good, apart from the 'standard' Rhino Mocks code below throws an exception:
public class MyBar : IBar {
//...
}
//...
var mockInstance = Mocks.DynamicMock<IFoo<MyBar>>();
This fails with an error:
System.TypeLoadException: Access is denied: 'IFoo`1[MyBar]'.
The problem is that the underlying BCL has a bug in Reflection Emit which causes it to generate invalid code. Oh dear. This has already been raised as an issue with MS - but they are failing to resolve it. Go and make your feelings heard!
Ayende has a workaround in Rhino Mocks 3.4 and above, so now you can write the following:
var mockInstance = Mocks.DynamicMockWithRemoting<Foo<MyBar>>();
This pushes the creation of the mock object through some additional hoops to bypass the BCL bug. Smart!