Tag Archives: C#

Another missing method for IEnumerable<T>

Currently there are two overloads for OrderBy on Enumerable:

  • OrderBy(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
  • OrderBy(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector, IComparer<TKey> comparer)

Because i don’t want to implement an IComparer<TKey> each time i have implemented the following class:

class DelegateComparer<t> : IComparer<t>
{
 public Func<t, T, int> CompareFunction { get; set; }

 public DelegateComparer(Func<t, T, int> compareFunction)
 {
  CompareFunction = compareFunction;
 }

 public int Compare(T x, T y)
 {
  return CompareFunction(x, y);
 }
}

And now i can define a nice extension method:

public static IOrderedEnumerable<tsource> OrderBy<tsource, TKey>(this IEnumerable<tsource> source, Func<tsource, TKey> keySelector, Func<tkey, TKey, int> compareFunction)
{
 var comparer = new DelegateComparer<tkey>(compareFunction);
 return source.OrderBy(keySelector, comparer);
}

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;
 }
}

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;
  }
 }
}

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();
 }
}

Ninject: connect an IProxyFactory component to the kernel

Because it’s the second time that i run into this i will post the solution here so that i (and all the other people that run into the same issue) can easily solve it next time. Anyway, i was playing with Ninject and ran into the following exception:

Error activating XXX: the implementation type YYY requests static interceptors, or dynamic interceptors have been defined.
In order to provide interception, you must connect an IProxyFactory component to the kernel.

If you search for implementations of IProxyFactory you will find the DynamicProxy2ProxyFactory and the LinFuProxyFactory classes. But how can you tell your kernel to use them? This is pretty simple (but hard to find on the web):

Kernel.Components.Connect<iproxyFactory>(new DynamicProxy2ProxyFactory());

Instead of writing this code to connect the ProxyFactory implementation you can also use the XXX module (which does it for you) as following:

var kernel = new StandardKernel(new DynamicProxy2Module(), new BusinessModule());

In case you really have to Append one array to another

Here is another problem i’ve seen people solve once too many: Append one array to another. STOP. Revisit the problem. Can’t you simply use List<T> and move on to solving actual business problems? In case you really can’t get rid of the arrays read the following:

Given()
{
 source = new[] { SourceElement };
 destination = new[] { DestinationElement };
}


When()
{
 source.AppendTo(ref destination);
}


ThenTheDestinationShouldStillHaveTheDestinationElement()
{
 Assert.AreEqual(DestinationElement, destination[0]);
}


ThenTheDestinationShouldHaveBeenExtendedWithTheSourceElement()
{
 Assert.AreEqual(SourceElement, destination[1]);
}

And here is the code which satisfies the requirements:

public static class Extensions
{
 public static void AppendTo<t>(this T[] sourceArray, ref T[] destinationArray)
 {
  var sourceLength = sourceArray.Length;
  var destinationLength = destinationArray.Length;
  var extendedLength = destinationLength + sourceLength;
  Array.Resize(ref destinationArray, extendedLength);
  Array.Copy(sourceArray, 0, destinationArray, destinationLength, sourceLength);
 }
}

Perhaps it’s time to start (or does it exist already, cause i can’t find it) an open-source project with extension methods.

Easy pattern for Control state

If you have decided that your WebControl requires to maintain it’s state you will want to figure out how to implement Control state. Most examples on the web will then create an array of objects and then hardcode the indices to find stuff back… Simply define a serializable inner class and use that instead of the ‘magic array object’. Eg:

class SilverlightHost : WebControl
{
 [Serializable]
 class State
 {
  public object BaseState { get; set; }
  public string SilverlightUrl { get; set; }
  public string SilverlightErrorHandlerUrl { get; set; }
  public Dictionary<string, string> Parameters { get; set; }
 }

 protected override void OnInit(EventArgs e)
 {
  base.OnInit(e);
  Page.RegisterRequiresControlState(this);
 }

 protected override object SaveControlState()
 {
  var state = new State
  {
   BaseState = base.SaveControlState(),
   SilverlightUrl = SilverlightUrl,
   SilverlightErrorHandlerUrl = SilverlightErrorHandlerUrl,
   Parameters = parameters
  };
  return state;
 }

 protected override void LoadControlState(object savedState)
 {
  var state = (State)savedState;
  SilverlightUrl = state.SilverlightUrl;
  SilverlightErrorHandlerUrl = state.SilverlightErrorHandlerUrl;
  parameters = state.Parameters;
  base.LoadControlState(state.BaseState);
 }
}