Verify that a X509Certificate can be used for key exchange

Here is another method that earned it’s place in my ever growing toolbox:

public static bool CanDoKeyExchange(this X509Certificate2 certificate)
{
 if (!certificate.HasPrivateKey) return false;

 var privateKey = certificate.PrivateKey as RSACryptoServiceProvider;
 if (privateKey == null) return false;

 var canDoKeyExchange = privateKey.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange;
 return canDoKeyExchange;
}

Presenting ValueType<T>

Here is a base class for some code that i have written once too many in my life: (In case you’re an early adaptor (.Net 4.0) you may want to use System.Tuple<T1> as base class)

public class ValueType<T> : IComparable, IComparable<ValueType<T>>, IEquatable<ValueType<T>>
 where T : IComparable<T>
{
 protected T Value { get; private set; }public ValueType(T value)
 {
  Value = value;
 }

 public override int GetHashCode()
 {
  return Value.GetHashCode();
 }

 public override string ToString()
 {
  return Value.ToString();
 }

 public override bool Equals(object obj)
 {
  return Equals(obj as ValueType<T>);
 }

 public bool Equals(ValueType<T> other)
 {
  return Compare(this, other) == 0;
 }

 public int CompareTo(object obj)
 {
  return CompareTo(this, obj as ValueType<T>);
 }

 public int CompareTo(ValueType<T> other)
 {
  return Compare(this, other);
 }

 static int Compare(ValueType<T> instance1, ValueType<T> instance2)
 {
  if (ReferenceEquals(instance1, instance2)) return 0;
  if (ReferenceEquals(instance1, null)) return -1;
  if (ReferenceEquals(instance2, null)) return 1;

  if (ReferenceEquals(instance1.Value, instance2.Value)) return 0;
  if (ReferenceEquals(instance1.Value, null)) return -1;
  if (ReferenceEquals(instance2.Value, null)) return 1;

  return instance1.Value.CompareTo(instance2.Value);
 }

 public static bool operator ==(ValueType<T> instance1, ValueType<T> instance2)
 {
  return Compare(instance1, instance2) == 0;
 }

 public static bool operator !=(ValueType<T> instance1, ValueType<T> instance2)
 {
  return !(instance1 == instance2);
 }

 public static bool operator <(ValueType<T> instance1, ValueType<T> instance2)
 {
   return Compare(instance1, instance2) < 0;
 }

 public static bool operator >(ValueType<T> instance1, ValueType<T> instance2)
 {
   return Compare(instance1, instance2) > 0;
 }
}

Do we need an EventAggregator when we have an IOC container?

An Event Aggregator is an example of a Publish/Subscribe channel. A while ago i started wondering if we still need an Event Aggregator in our compisite applications if we have an IOC container that takes cares of dependency wiring. An IOC container can easily inject the Event/MessageHandler(s) in the Event/MessagePublisher(s)… I’m still not sure about the answer (Yes/No).

About dependencies

This weekend i noticed a couple of posts by Uncle Bob trying to get some discussions going. In Mocking Mocking and Testing Outcomes at some point he generates a fake of some class

“Oh, ick!” you say. Yes, I agree it’s a lot of code. On the other hand, it took me just a single keystroke on my IDE to generate all those dummy methods. (In IntelliJ it was simply command-I to implement all unimplemented methods.) So it wasn’t particularly hard. And, of course, I can put this code somewhere where nobody had to look at it unless they want to. It has the advantage that anybody who knows Java can understand it, and can look right at the methods to see what they are returning. No “special” knowledge of the mocking framework is necessary.

So adding a lot of generated code, which no-one should ever look at, is better than a mocking framework? Hahaha, why would i want to repeat myself creating all those fake objects? (DRY)

Another problem that i have with his example is the fact that the ‘dependency’ has a ton of methods that are not used by the consumer, so it makes me wonder: why are those methods there? Define an interface for the required methods, and have your consumer use that interface instead. This way you don’t have to look at those unused methods which only clutter the API.

A second read made it clear that Uncle Bob is talking about unit-tests, which are typically implemented as state-based tests. In case you’re doing integration tests, you will have (more) dependencies and want to verify the interaction between your system under test and the dependencies. And that is (imho) the scenario where mocking frameworks really shine :)

About forced design

if you need typemock your design is wrong.

Although i understand what people are trying to say with that quote, it’s wrong on many levels. I pretty much agree with everything that Roy wrote in Test driven design – Willed vs. Forced Designs. As some commenters pointed out it is hard to convince management that they need an isolation framework, let alone that they have to pay for one.

A couple of thoughts:

  • What about Pex Stubs & Moles? It uses the profiling API (less limitations than rhino/moq/…) too and for a lot of shops doing .Net development it’s free.
  • I really don’t understand people that are unwilling to pay for tools that can contribute to the generation of business value (eg: Resharper, NCover, NDepend, …) when they don’t come from Microsoft.
  • Filling up gaps in the .Net/Microsoft space seems like an awful business model.

Programming the Bus Pirate with C#

A while ago i received my Bus Pirate from Seeed Studio Depot. In essence it is a universal serial bus interface and i would love to program it using c#. I know that i can use the DataReceived event and then fiddle with bits (read here if you’re into that kind of self-punishment) but spawning a separate thread to do the blocking work is ten times less work to get it up and running:

static void Main()
{
 using (var serialPort = new SerialPort("COM9", 115200, Parity.None, 8, StopBits.One))
 {
  serialPort.Open();
 
  new Thread(() => WriteLinesFrom(serialPort)).Start();

  while (true)
  {
   var command = Console.ReadLine();
   if (command == "EXIT") break;
   serialPort.WriteLine(command);
  }
 }
}

static void WriteLinesFrom(SerialPort serialPort)
{
 try
 {
  while (true) Console.WriteLine(serialPort.ReadLine());
 }
 catch (Exception)
 {
  break;
  }
 }
}

Add “Run as administrator” to .sln files

Another trick i learned from the “How-To Geek” is how to add a “Run as administrator” option in the windows shell for .sln files which makes life considerably easier ;)

About raising events

Very often i see people write the following to ’safely’ raise a method:

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
 if (Stopped != null) Stopped(this, EventArgs.Empty);
}

Some developers think that they should program defensively and avoid the potential concurrency problem:

public event EventHandler Stopped;

void RaiseStoppedEvent()
{
 var handler = Stopped;
 if (handler!= null) handler(this, EventArgs.Empty);
}

And then there is Tim’s way to raise an event: (If i’m not mistaken it was Ayende who once blogged about this)

public event EventHandler Stopped = delegate { };

void RaiseStoppedEvent()
{
 Stopped(this, EventArgs.Empty);
}

Creating graphs with the Silverlight Toolkit

As i wrote already: In a chart the elements on the X-axis are usually numbers or dates, and the elements on the Y-axis are usually doubles. We can define such a combination as following:

public class Point<T>
{
 public T X { get; set; }
 public double Y { get; set; }
}

Here is a little helper function for creating line series that are used by the Silverlight Toolkit:

public LineSeries Create<T>(string title, Series<T> series, Func<T, double> f) where T : IComparable<T>
{
 var points = series.Select(x => new Point<T> { X = x, Y = f(x) });

 var lineSeries = new LineSeries
 {
  Title = title,
  ItemsSource = points,
  IndependentValuePath = "X",
  DependentValuePath = "Y"
 };

 return lineSeries;
}

Given all this infrastructure we can easily draw the graph of a function:

public MainPage()
{
 InitializeComponent();

 var series = 0.To(100);

 Func<int, double> multiplyByTwo = x => 2 * x;
 Chart1.Series.Add(Create("2x", series, multiplyByTwo));

 Func<int, double> multiplyByThree = x => 3 * x;
 Chart1.Series.Add(Create("x/2", series, multiplyByThree));
}

Here is how the result looks like (too much data on the chart):

screenshot of chart in silverlight toolkit

Creating series of elements

Lately i have done quite a bit of charting. Very often the X-axis is populated with a series of numbers or dates. This can be as simple as: (My very little DSL in Jeremy D. Miller Style)

[Test] public void ShouldBeAbleToGetSeriesOfNumbers()
{
 // Arrange
 var series = 3.To(5);

 // Act
 var elements = series.Elements;

 // Assert
 var expected = new[] { 3, 4, 5 };
 CollectionAssert.AreEqual(expected, elements);
}

[Test] public void ShouldBeAbleToGetSeriesOfDays()
{
 // Arrange
 var now = DateTime.Now.Date;
 var twoDaysLater = now.AddDays(2);
 var series = now.To(twoDaysLater);

 // Act
 var elements = series.Elements;

 // Assert
 var expectedDays = new[] { now, now.AddDays(1), now.AddDays(2) };
 CollectionAssert.AreEqual(expectedDays, elements);
}

And here is the code that makes these tests pass:

public static class Series
{
 public static Series<int> To(this int from, int to)
 {
  return Create(from, to);
 }

 public static Series<DateTime> To(this DateTime from, DateTime to)
 {
  return Create(from, to);
 }

 public static Series<DateTime> Create(DateTime from, DateTime to)
 {
  return new Series<DateTime>(from.Date, to.Date, d => d.AddDays(1));
 }

 public static Series<DateTime> Create(DateTime from, int numberOfDays)
 {
  return Create(from.Date, from.Date.AddDays(numberOfDays));
 }

 public static Series<int> Create(int from, int to)
 {
  return new Series<int>(from, to, n => n + 1);
 }

 public static Series<int> Create(int from, int to, int stepSize)
 {
  return new Series<int>(from, to, n => n + stepSize);
 }
}

public class Series<T> : IEnumerable<T> where T : IComparable
{
 public T From { get; private set; }
 public T To { get; private set; }
 public Func<T, T> Step { get; private set; }

 public Series(T from, T to, Func<T, T> step)
 {
  From = from;
  To = to;
  Step = step;
 }

 public IEnumerable<T> Elements
 {
  get
  {
   var current = From;
   while (current.CompareTo(To) <= 0)
   {
    yield return current;
    current = Step(current);
   }
  }
 }

 public IEnumerator<T> GetEnumerator()
 {
  return Elements.GetEnumerator();
 }

 IEnumerator IEnumerable.GetEnumerator()
 {
  return GetEnumerator();
 }
}