Friday, 1 December 2017

Mock IAwaitable

When ever you are unit testing chatbots in the botnet framework it's common place to wait for some feedback from the user.

public async Task StartAsync(IDialogContext context)
{
    //display feedback card
    var feedbackCard = base.GetFeedbackMessage(context.MakeMessage(), Contact);
    await context.PostAsync(feedbackCard);

    //wait for feedback
    context.Wait(GetFeedbackAsync);

}

then your GetFeedbackAsync method would look something like

internal async Task GetFeedbackAsync(IDialogContext context, IAwaitable<object> result)
{
    // Stuff to do
    context.Done(null);

}

now the problem is in the IAwaitable<object>, this has to be mocked

private Mock<IAwaitable<IMessageActivity>> GetMoqAwaitableMessageActivity(string textMessage)
{
    var moqMessage = new Mock<IMessageActivity>(MockBehavior.Loose);
    moqMessage.Setup(x => x.Text)
        .Returns(textMessage);

    var moqAwaiter = new Mock<IAwaiter<IMessageActivity>>(MockBehavior.Loose);
    moqAwaiter.Setup(x => x.GetResult())
        .Returns(() => moqMessage.Object);
    moqAwaiter.Setup(x => x.IsCompleted)
        .Returns(true);
           
    var moqAwaitable = new Mock<IAwaitable<IMessageActivity>>();
    moqAwaitable.Setup(x => x.GetAwaiter())
        .Returns(() => moqAwaiter.Object);

    return moqAwaitable;

}

Without getting to in depth into how to implement the async/await syntactical sugar, before mocking IAwaitable we also need to mock IAwaiter and ensure that the IsCompleted property returns true.

now we can test our GetFeedbackAsync method

[TestMethod]
public async Task Dialog_Feedback_Text_Jibberish()
{
    //arange
    var moqDialogContext = GetMoqDialogContext();
    var moqAwaitableMessage = GetMoqAwaitableMessageActivity("bla bla bla");
    var feedbackDialog = new FeedbackDialog();

   //act
    await feedbackDialog.GetFeedbackAsync(moqDialogContext.Object, moqAwaitableMessage.Object);

   //assert
    moqDialogContext.Verify(x => x.PostAsync(It.IsAny<IMessageActivity>(), default(CancellationToken)), Times.Exactly(2));
    moqDialogContext.Verify(x => x.Wait(It.IsAny<ResumeAfter<IMessageActivity>>()), Times.Once);
}


Obviously your assert section will vary, but by mocking the context and the iawaitable we can achieve some degree of unit testing. 

Oh and if you don't know i'm using the Moq nuget package.

Wednesday, 29 November 2017

Simple Factory Pattern

The simple factory pattern is probably the most common pattern you'll ever see; it's fairly simple in concept and implementation. It can be thought of as a central location to create instances of objects. take a look at the following example.

interface IHourly
{
    double HourlyRate { get; set; }
}

interface ISalery
{
    int Salery { get; set; }
    double Bonus { get; }
}

class Person
{
    static int runningId = 0;
    public int Id { get; } = runningId++;
    public string Name { get; set; }
    public override string ToString() => $"{Id}) {Name}";
}

class EmployeePersonIHourly
{
    public double HourlyRate { get; set; }
    public override string ToString() => $"{base.ToString()} ${HourlyRate * 40 * 52}";
}

class PartnerPersonISalery
{
    public int Salery { get; set; }
    public double Bonus { get => 1.1; }
    public override string ToString() => $"{base.ToString()} ${Salery * Bonus}";

}

what we have above is three objects  Person, Employee and Partner; Person is the common base for employee and partner. Now if we had an array of strings that represented various partners and employees such as the following.

class Program
{
    static void Main(string[] args)
    {
        var staffFactory = new StaffFactory();
        var data = new [] { "Pawel $100000", "Magda $150000", "Marin $50.00", "Bryne $45.53" };
    }

}

it would prove to be a pain to extract the data parse it, decide whether it's an employee or a partner then create an instance of that object, well it's only natural to create a function to do that grunt work for use, and hence a factory.

class StaffFactory
{
    public Person ParseStaff(string data)
    {
        var dataValues = data.Split(' ');
        dataValues[1] = dataValues[1].TrimStart('$');
        double wage;
        int salery;

        if (int.TryParse(dataValues[1], out salery))
            return new Partner { Name = dataValues[0], Salery = salery };
        else if (double.TryParse(dataValues[1], out wage))
            return new Employee { Name = dataValues[0], HourlyRate = wage };

        return null;
    }
}

class Program
{
    static void Main(string[] args)
    {
        var staffFactory = new StaffFactory();
        var data = new string[] { "Pawel $100000", "Magda $150000", "Marin $50.00", "Bryn $45.53" };

        foreach (var d in data)
            Console.WriteLine(staffFactory.ParseStaff(d).ToString());
    }
}

an tada, that's all there really is to a simple factory pattern, it's just a function that takes in some parameters and returns objects. One caveat to mention is that there is such a thing as a Factory Method Pattern, in which the only difference is that the factory adheres to an abstraction.

Wednesday, 15 November 2017

Decorator Pattern

The decorator pattern lets us add functionality to objects dynamically without modifying those objects, it lends itself naturally to the support of legacy systems because it facilitates adding functionality without modifying existing classes it's an alternative to sub-classing.

The decorator pattern has a base implementation at the very core, then it's wrapped by various decorators which extend the nested objects behavior.

the definition of the Decorator pattern is: The decorator attaches additional responsibilities to an object dynamically, decorators provide a flexible alternative to sub-classing for extending functionality. 

what it does is lets us wrap objects and extend object members, it doesn't have to replace behavior, but can extend it, or just replace it depends on your needs. So for example if had some sort of object that made some sort of calculation, and you wanted to modify the result of that calculation, then you could wrap that original object with a decorator that would then modify the result in some fashion.

let's take a look at the UML for this


the big take away is when looking at the relationship between the IWidget and IDecorator interfaces, the IDecorator not only has a reference to an IWidget it also inherits from it, meaning that it has both "has as" and "is a" relationship with the IWidget class. this allows us to wrap a widget within multiple decorators each time extending or modifying it's behavior.

Let's take a look at a couple generic examples to wrap our heads around this concept, to get started take a look at the following interface

interface IWidget
{
    string Name { get; set; }
    double Price { get; set; }
}

simple enough we define two properties for our IWidget interface, next let's create an IWidgetDecorator.

interface IWidgetDecorator  : IWidget
{
    IWidget widget { get; }
}

now here it gets a bit interesting, not only does our IWidgetDecorator have an instance of IWidget, but it also inherits from the IWidget interface; which results in

class WidgetDecoratorIWidgetDecorator  
{
    public IWidget widget => throw new NotImplementedException();
    public string Name {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }
    public double Price {
        get => throw new NotImplementedException();
        set => throw new NotImplementedException();
    }
}

What we end up with is a concrete class that has an IWidget property as well as implementations for all of the members of IWidget; this lets us maintain a reference to a inner widget while letting us modify the inner widgets properties from the decorator that engulfs the widget. this approach also let's us nest multiple decorators around a single widget. Let's take a look at a defined WidgetDecorator class

class WidgetDecoratorIWidgetDecorator  
{
    public IWidget innerWidget{ get; private set; }

    string name;
    public string Name
    {
        get => $"{widget.Name} {this.name}";
        set => this.name = value; 
    }

    double price;
    public double Price
    {
        get => widget.Price + price;
        set => this.price = value; 
    }

    public WidgetDecorator(IWidget innerWidget, string name, double price)
    {
        this.innerWidget innerWidget;
        this.Name = name;
        this.Price = price;
    }
}

Now here we can see that we have a constructor that takes in an inner widget and a name and price for the decorator, then in the decorators properties we modify the inner widgets properties with the decorators values.

Now let's put our contrived example together with some execution code.

using System;

namespace pav.decoratorPattern
{
    interface IWidget
    {
        string Name { get; set; }
        double Price { get; set; }
    }

    interface IWidgetDecoratorIWidget
    {
        IWidget innerWidget { get; }
    }

    class WidgetIWidget
    {
        public string Name { get; set; }
        public double Price { get; set; }

        public Widget(string name, double price)
        {
            this.Name = name;
            this.Price = price;
        }
    }

    class WidgetDecoratorIWidgetDecorator 
    {
        public IWidget innerWidget { get; private set; }

        string name;
        public string Name
        {
            get => $"{innerWidget.Name} {this.name}";
            set => this.name = value; 
        }

        double price;
        public double Price
        {
            get => innerWidget.Price + price;
            set => this.price = value; 
        }

        public WidgetDecorator(IWidget innerWidget, string name, double price)
        {
            this.innerWidget = innerWidget;
            this.Name = name;
            this.Price = price;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var widget = new Widget("Base Widget", 1);
            var d1 = new WidgetDecorator(widget, "Decorator one", .25);
            var d2 = new WidgetDecorator(d1, "Decorator two", .45);

            Console.WriteLine($"D1: {d1.Name} {d1.Price}");
            Console.WriteLine($"D2: {d2.Name} {d2.Price}");
        }
    }
}

Now when we execute our application we see the following result


Just as our logic defines with each layered decorator we concat all the widget names and add up their prices.

Next let's look at another contrived example but this time instead of using an interface let's use an abstract class as our abstraction. We're going go build an application for a used car lot.

Let's get started by defining our abstract Car class

abstract class Car
{
    public abstract string Name { get; set; }
    public abstract string Make { get; set; }
    public abstract int Cost { get; set; }
}

we sell basic cars that implement the car abstract class

class SedanCar
{
    public override string Name { get; set; }
    public override string Make { get; set; }
    public override int Cost { get; set; }
}

class CoupeCar
{
    public override string Name { get; set; }
    public override string Make { get; set; }
    public override int Cost { get; set; }
}

class VanCar
{
    public override string Name { get; set; }
    public override string Make { get; set; }
    public override int Cost { get; set; }
}

So to use what we have thus far we'd simply, instantiate our car and find out the cost by calling the cost property, now realistically we'd have some business logic that would take in a cost and return a price to sell for, but lets keep it simple.

class Program
{
    static void Main(string[] args)
    {
        Car van = new Van { Make = "Ford", Name = "Windstar", Cost = 500 };
        Console.WriteLine(van.Cost);
    }

}

To drum up some more revenue what we want is to offer some "Options" to spruce up old used cars, for example offer a paint job, or maybe even let the customer purchase a warranty.

We want to add options to our cars but we don't want to modify our old Car class or any of its sub classes, so to do this we can create a "Decorator"

abstract class CarDecorator : Car
{
    Car _car;
    public CarDecorator(Car Car) => _car = Car;
    public override string Name { get => _car.Name; set => _car.Name = value; }
    public override string Make { get => _car.Make; set => _car.Make = value; }
    public override int Cost { get => _car.Cost; set => _car.Cost = value; }

}

Now our "Decorator" implements our car abstraction and wraps an instance of car. after that we can create our "Options" by inheriting from our decorator

class WarentyOptionCarDecorator
{
    public WarentyOption(Car Car) : base(Car) { }
    public override int Cost => base.Cost + 500;
}

class PaintJobOptionCarDecorator
{
    public PaintJobOption(Car Car) : base(Car) { }
    public override int Cost => base.Cost + 250;
}

Now to use this we just have to pass our existing car class into our decorators to let

class Program
{
    static void Main(string[] args)
    {
        Car van = new Van{ Make = "Ford", Name = "Windstar", Cost = 500 };
        van = new WarentyOption (van);
        van = new PaintJobOption (van);
        Console.WriteLine(van.Cost);

        Car sedan new Sedan{ Make = "Ford", Name = "Escort", Cost = 250 };
        sedan new WarentyOption (sedan);
        sedan new PaintJobOption (sedan);
        Console.WriteLine(sedan.Cost);
    }
}

Now by running our initial car instance through all of the decorators we've updated the car cost property, without modify our original classes or any of the code that would need them to function.

Both of the above examples convey the Decorator pattern in it's simplest form, however the decorator pattern is not meant to modify properties but more so behaviors, here's a shape example in which we start with a circle and then wrap it in various decorators to find the surface area of a cylinder and sphere.

using System;

namespace pav.decoratorPatternSurfaceArea
{
    interface ICircle
    {
        double Arg { get; set; }
        double GetSurfaceArea();
    }

    interface I3DShapeDecorator : ICircle
    {
        ICircle BaseShape { get; }
    }

    class Circle : ICircle
    {
        public double Arg { get; set; }

        public Circle(double radius) => Arg = radius;
       
        //A=πr2
        public double GetSurfaceArea() => Math.PI * Math.Pow(Arg, 2);
    }

    class Cylinder : I3DShapeDecorator
    {
        public ICircle BaseShape { get; private set; }
        public double Arg { get; set; }

        public Cylinder(Circle circle, double height)
        {
            BaseShape = circle;
            Arg = height;
        }

        //A=πr2 * h
        public double GetSurfaceArea() => BaseShape.GetSurfaceArea() * Arg;

    }

    class Sphere : I3DShapeDecorator
    {
        public ICircle BaseShape { get; private set; }
        public double Arg { get; set; }

        public Sphere(Circle circle)
        {
            BaseShape = circle;
            Arg = 4;
        }

        //A=πr2 * 4
        public double GetSurfaceArea() => BaseShape.GetSurfaceArea() * Arg;
    }

    class Program
    {
        static void Main(string[] args)
        {
            var circle = new Circle(5);
            var sphere = new Sphere(circle);
            var cylinder = new Cylinder(circle, 2);

            Console.WriteLine($"Circle SA:{circle.GetSurfaceArea()}");
            Console.WriteLine($"Sphere SA:{sphere.GetSurfaceArea()}");
            Console.WriteLine($"Cylinder SA:{cylinder.GetSurfaceArea()}");
        }
    }

}

however  again this isn't the best example because ideally you would want to nest multiple decorators each one building on the result of the previous to really leverage this pattern.

An appropriate problem that comes to mind is parsing a CSV file, let's say that you create an application that parses values out of a csv line by line, but somewhere down the line the csv file evolves and some of the lines in it now contain more information well you could wrap your original parser in a decorator, the original parser would handle the original file and the decorator could deal with a newer version of the file and as more and more versions of the CSV schema came to light you would wrap your original parser in more and more decorators thus maintaining backwards compatibility and handling newer versions