Tuesday, March 15, 2011

Geometry and Mini-Language

StreamGeometry is a light-weight alternative to the PathGeometry class for
creating complex geometric shapes. You can use StreamGeometry when you
need to describe a complex geometry but don’t want the overhead of supporting
data binding, animation, and modification.

There are two classes in WPF that provide the mini-language for describing
geometric paths: StreamGeometry, and PathFigureCollection. You need to use
the StreamGeometry mini-language when you set a property of the Geometry
type, such as the Data property of a Path element.

<path stroke="Blue" data="M 100 120 L 200 120 L 200 220 L 100 170">
</path>


This path uses a sequence of four commands. The first command, M, creates the
PathFigure and sets the starting point to (100, 120). The following three
commands (L) create line segments.

See also Mini-Language in MSDN
From the book of Practical WPF Graphics Programming



L endPoint : The end point of the line.
H x : The x-coordinate of the end point of the line.
V y : The y-coordinate of the end point of the line.

F0 specifies the EvenOdd fill rule.
F1 specifies the Nonzero fill rule.
An uppercase M indicates that startPoint is an absolute value; a lowercase m indicates that startPoint is an offset to the previous point

C controlPoint1 controlPoint2 endPoint : Cubic Bezier Curve Command
A size rotationAngle isLargeArcFlag sweepDirectionFlag endPoint : Creates an elliptical arc between the current point and the specified end point.

Z : Ends the current figure and creates a line that connects the current point to the starting point of the figure.

Friday, March 11, 2011

Did i say "I've got memory leak"?

Dealing with memory leak is not as far as some might think it is. But it doesn't get serious until it is very late to change the fundamentals of our software design.

In my recent project it happened to be caused by traditional event subscription pattern. Which is most likely not leaving any memory leak behind, but it could easily do so :-(

I also looked into latest libraries of Microsoft and saw they are using a new way of subscribing event handler to GUI events in WPF. Further I saw that every Window, like any Visual object in WPF, is derrived from DispatcherObject and is also implementing IWeakEventListener; hummmmmm!

So I've decided to create my first WeakEventManager and followed the instructions by Reed Copsey Jr. in his blog

You can instanciate several instances of different event listeners and let the manager route the events to all of them. As long as they all implement IWeakEventListener.ReceiveWeakEvent


To demonstrate this I started a sample code about human body. Assume you have a heart class and a hand class. If you have an instance of them and you need to get events on your hand when the heart beats you might do something like:
hear.BeatEvent += right.BeatHandler
The idea is to change this aby using an event manager, in my sample I have called it Brain, to handle de notifications like
Brain.AddListener(heart, right);
And to unsubscribe to the event you do something like
Brain.RemoveListener(heart, right);


To make this possible, you need to make sure that your Hand class where the events need to be handled, you implement the IWeakEventListener interface which brings us to ReceiveWeakEvent method:

/// <summary> Receives events from the centralized event manager. </summary>
/// <returns> true if the listener handled the event. </returns>
/// <param name="managerType">The type of the <see cref="T:System.Windows.WeakEventManager"/> calling this method.</param>
/// <param name="sender">Object that originated the event.</param>
/// <param name="e">Event data.</param>
public bool ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
{
if (managerType == typeof(Brain))
{
var beat = e
as BeatArgs;
Trace.WriteLine(
string.Format("{0} hand is getting the beat from {1}", name, beat.TimeOfBeat.ToString("hh:mm:ss")));
return true;
}

return false;
}

The Brain class which has a Singleton implementation provides only two public methods i.e. AddListener and RemoveListener. They do this by calling the protected methods and passing the parameters:

/// <summary>Subscribe a body part to listen to heart beat </summary>
/// <param name="source">the heart to listen to</param>
/// <param name="listener">the body that subscribes</param>
public static void AddListener(Heart source, IWeakEventListener listener)
{
Neuron.ProtectedAddListener(source, listener);
}

/// <summary>Unsubscribe a body part to listen to heart beat </summary>
/// <param name="source">the heart to listen to</param>
/// <param name="listener">the body that subscribes</param>
public static void RemoveListener(Heart source, IWeakEventListener listener)
{
Neuron.ProtectedRemoveListener(source, listener);
}

That is not all what brain do internally. It is actually inheriting the abstract class WeakEventManager and in order to do that it overrides the StartListening and StopListening methods that are internally called when it should be.

/// <summary>Starts listening on the provided heart for the managed beat event.</summary>
/// <param name="source">The heart to disconnect beat event</param>
protected override void StartListening(object source)
{
var heart = source
as Heart;
if (heart == null) throw new ArgumentException("The brain suppose to listen to heart only");

heart.BeatEventHandler += DeliverEvent;
}

/// <summary>Stops listening on the provided heart for the managed beat event.</summary>
/// <param name="source">The heart to disconnect beat event</param>
protected override void StopListening(object source)
{
var heart = source
as Heart;
if (heart == null) throw new ArgumentException("The brain suppose to listen to heart only");

heart.BeatEventHandler -= DeliverEvent;
}


The last part is the Heart where the event is getting fired. That is nothing special and can be implemented as before.

/// <summary> Can beat and can e subscribed to the beat event handler </summary>
public partial class Heart
{
/// <summary>Hanldler for notifying a beat </summary>
public event EventHandler<BeatArgs> BeatEventHandler;

/// <summary>Sends the beat through the events </summary>
/// <param name="beatArgs"></param>
protected void OnSendBeat(BeatArgs beatArgs)
{
if (BeatEventHandler != null)
BeatEventHandler(
this, beatArgs);
}

/// <summary>Create a beat and send it </summary>
private void BeatOnce()
{
OnSendBeat(
new BeatArgs());
}
}


Friday, March 4, 2011

Behavior Driven Development

Dan North in his blog about Behavior Driven Development write the following:

" If we could develop a consistent vocabulary for analysts, testers, developers, and the business, then we would be well on the way to eliminating some of the ambiguity and miscommunication that occur when technical people talk to business people."
He describes BDD as follows:

"BDD is a second-generation, outside-in, pull-based, multiple-stakeholder, multiple-scale, high-automation, agile methodology. It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters."

The practices of BDD include:

  • Establishing the goals of different stakeholders required for a vision to be implemented
  • Drawing out features which will achieve those goals using feature injection
  • Involving stakeholders in the implementation process through outside-in software development
  • Using examples to describe the behavior of the application, or of units of code
  • Automating those examples to provide quick feedback and regression testing
  • Using 'should' when describing the behavior of software to help clarify responsibility and allow the software's functionality to be questioned
  • Using 'ensure' when describing responsibilities of software to differentiate outcomes in the scope of the code in question from side-effects of other elements of code.
  • Using mocks to stand-in for collaborating modules of code which have not yet been written