Wednesday, January 24, 2018

Partitioning of application into main modules

Application should be partitioning to main modules.

For example, i will consider train system.
It is consists from: Train, routes, stations, search train, add route, rich WPF UI, console UI, user click some button to get stations etc.

DO - domain object. It is anemic entity, consists only Train, Route, Station
BL - business logic. It is operations on DO: search route, serialization/deserialization of DO objects etc.
UI - is how all this looks like on screen. Can be made by WPF, WinForms, Console etc.

How knows who?

DO do not know anyone.
BL knows DO only.
UI knows both BL and DO.

Its very superficial review, but it is very important to understand this concept

Tuesday, August 8, 2017

Dependency Injector NINJECT full example

Here is example of library, using Ninject and also test

Library:

using Ninject;
using Ninject.Modules;

namespace NinjectExample
{
    #region Interface
    public interface IProduct
    {
        string InsertProduct();
    }
    #endregion

    #region Interface implementation
    public class ConcreteProduct1 : IProduct
    {
        public string InsertProduct()
        {
            string value = "Dependency 1 injection using Ninject";
            return value;
        }
    }

    public class ConcreteProduct2 : IProduct
    {
        public string InsertProduct()
        {
            string value = "Dependency 2 injection using Ninject";
            return value;
        }
    }
    #endregion

    #region Dependency Injector
    internal class ProductsBinder : NinjectModule
    {
        private string _productName;

        public ProductsBinder(string productName)
        {
            _productName = productName;
        }

        public override void Load()
        {
            switch (_productName)
            {
                case "DataAccessLayer1":
                    Bind<IProduct>().To<ConcreteProduct1>();
                    break;
                case "DataAccessLayer2":
                    Bind<IProduct>().To<ConcreteProduct2>();
                    break;
            }
        }
    }
    #endregion

    #region Factory
    public class FactoryProduct
    {
        public static IProduct Create(string name)
        {
            IKernel krn = new StandardKernel(new ProductsBinder(name));
            return krn.Get<IProduct>();
        }
    }
    #endregion
}

Test:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using NinjectExample;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            IProduct dl = FactoryProduct.Create("DataAccessLayer1");
            Assert.AreEqual("Dependency 1 injection using Ninject", dl.InsertProduct());
        }

        [TestMethod]
        public void TestMethod2()
        {
            IProduct dl = FactoryProduct.Create("DataAccessLayer2");
            Assert.AreEqual("Dependency 2 injection using Ninject", dl.InsertProduct());
        }
    }
}

Of course, all tests passed. 

Monday, August 7, 2017

Dependency Injector NINJECT

Hello
Stuff, i learned recently

For example, there is peace of code:

public partial class MainWindow : Window
{
ISubject _subject;

public MainWindow()
{
_subject = new WeatherData();
}

.... other code....
}


What is a problem with this code?
a couple of.
1. MainWindow should to know about ISubject realization. So, it violate OCP. Class MainWindow do some job and it also instantiate _subject by concrete realization.

2.  If i will want other _subject realization, i will open MainWindow and do changes. It is violates OCP.

3. It is not using Ninject dependency injector ;-)

So, how we fix it?

1. In Visual studio package manager console type :
PM> install-package Ninject

2. Create class, which bind interface and realization by using Ninject:
public class SubjectModule : NinjectModule
{
public override void Load()
{
Bind<ISubject>().To<WeatherData>();
}
}

what is mean, is realization of ISubject is WeatherData

3. Lets create some factory, which use SubjectModule :
public class SubjectFactory
{
public static ISubject Create()
{
IKernel krnl = new StandardKernel(new SubjectModule());
return krnl.Get<ISubject>();
}
}

4. lets do refactoring to MainWindow :
public partial class MainWindow : Window
{
ISubject _subject;

public MainWindow()
{
_subject = SubjectFactory.Create();
}
.... other code....
}

that all!
Now we can change Binding and get other realization inside of MainWindow  without change its code! And, from now, MainWindow  should not know anything about _subject concrete realization

Enjoy

P.S. thanks to Vova about make me to learn it

x

Thursday, June 22, 2017

.NET DocumentViewer FindToolBar customization

Hi
If you using MS .NET DocumentViewer and you want customize Find field

there some ways.
In my example i can change text "Type text to find..." to other one ("Find me!") and also disable alefHamza field

ContentControl findToolBar = documentViewer.Template.FindName("PART_FindToolBarHost", documentViewer) as ContentControl;
if (findToolBar == null) return;

Type baseType = findToolBar.Content.GetType();
MemberInfo[] dynMethod = baseType.GetMember("OptionsMenuItem", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo alefHamzaField = (dynMethod[0] as FieldInfo);
System.Windows.Controls.MenuItem menuItem = alefHamzaField.GetValue(findToolBar.Content) as System.Windows.Controls.MenuItem;
menuItem.Visibility = System.Windows.Visibility.Collapsed;

dynMethod = baseType.GetMember("FindTextLabel", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo findTextLabel = (dynMethod[0] as FieldInfo);
System.Windows.Controls.Label lbl = findTextLabel.GetValue(findToolBar.Content) as System.Windows.Controls.Label;
lbl.Content = "Find me!"

Thanks for watching!

Wednesday, December 31, 2014

Command design pattern. Simple version.

Hello
We have Light devices, which can beam or not.
We do not want control directly Light source, because we want learn Command Design Pattern :-)
Of course, the reasons is others. For example, we want to be less sensitive to changes.

In implementation of Command Design Patter in our example we have 3 players:

  • Device: is a Light which can be "ON" or "OFF" state.
  • Command turn "ON" the lights: is Light "ON" command. Is a class, which wraps above Light. Heart of this class - turn "ON" the Light, which encapsulated in single function "Execute". 
  • Remote: some class which got command and call it "Execute". When user call "Click Remote" of this class, its method call "Execute" of command
Illustration:




Code behind it:
public interface ICommand
{
    void Execute();
}

public class Light
{
    public void On()
    {
        Console.WriteLine("Light is ON");
    }

    public void Off()
    {
        Console.WriteLine("Light is OFF");
    }
}

public class LightOnCommand : ICommand
{
    private Light _light;

    public LightOnCommand(Light light)
    {
        _light = light;
    }

    public void Execute()
    {
        _light.On();
    }
}

public class SimpleRemoteControl
{
    ICommand _command;

    public void SetCommand(ICommand command)
    {
        _command = command;
    }

    public void ClickButton()
    {
        _command.Execute();
    }
}

Tester:
Light light = new Light();
ICommand lightOnCmd = new LightOnCommand(light);

SimpleRemoteControl remote = new SimpleRemoteControl();
remote.SetCommand(lightOnCmd);
remote.ClickButton();

Result:

Wednesday, December 17, 2014

Decorator Design Pattern - another example

Hi all

Another example of Decorator Design pattern implementation - create text decorator. For example, i create string. My goal - create architecture, which makes possible to change string on the fly - change register, remove spaces etc

My Unit Test shall looks like:

Component component = new LowerRegisterDecorator(new RemoveSpacesDecorator(new BaseString("MaMa PaPa")));
string text = component.Text();

Expected result: mamapapa

Lets coding
First of all, UML:

Code:

class BaseComponent.cs:

namespace TextDecorator
{
    public class BaseString : Component
    {
        private string _text;

        public BaseString(string text)
        {
            _text = text;
        }

        public override string Text()
        {
            return _text;
        }
    }
}

Class Component.cs:

using System;

namespace TextDecorator
{
    public abstract class Component
    {
        public abstract String Text();
    }
}

Class ComponentDecorator.cs:

namespace TextDecorator
{
    public abstract class ComponentDecorator : Component
    {
        protected Component _component;
        public ComponentDecorator(Component component)
        {
            _component = component;
        }
    }

    public class UpperRegisterDecorator : ComponentDecorator
    {
        public UpperRegisterDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().ToUpper();
        }
    }

    public class LowerRegisterDecorator : ComponentDecorator
    {
        public LowerRegisterDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().ToLower();
        }
    }
    
    public class RemoveSpacesDecorator : ComponentDecorator
    {
        public RemoveSpacesDecorator(Component component) : base(component) { }

        public override string Text()
        {
            return _component.Text().Replace(" ","");
        }
    }
}

Wednesday, December 11, 2013

Refactoring to Decorator design pattern.

Hello

There was post about it (decorator-design-pattern), but lets do it better.

First of all i wish do it w/o using Design patterns, but using usual OOP principles.

So, i am a AM General company, witch making Hummer H1 army cars.

Lets do it!
I wish create car with two fields: weight and description

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer() { }

 public int Weight
 {
  get { return 5000; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

Great!
After some time, US army wish complete the car with some additions: Xenon lights. Lets do it:

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer() { }

 public int Weight
 {
  get { return 5000; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public class CarExtraLights : IArmyCar
{
 public CarExtraLights() { }

 public int Weight
 {
  get { return 5020; }
 }

 public string Description
 {
  get { return "Hummer car + strong lights"; }
 }
}

Very simple. I just need remember how much kg in Hummer H1 when i do weight calculations and description of Hummer H1 when i return descriptions. But it does not gonna be changed FOR A NOW.

We sell very well cars to US army and do a lot of money.
After some time we get some new requirement. Texas state wish extra accumulator, because of Texas rangers like to play country music all the night in Hummer.
OK, no problem!

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer() { }

 public int Weight
 {
  get { return 5000; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public class CarExtraLights : IArmyCar
{
 public CarExtraLights() { }

 public int Weight
 {
  get { return 5020; }
 }

 public string Description
 {
  get { return "Hummer car + strong lights"; }
 }
}

public class CarExtraAccumulator : IArmyCar
{
 public CarExtraAccumulator() { }

 public int Weight
 {
  get { return 5100; }
 }

 public string Description
 {
  get { return "Hummer car + big accumulator"; }
 }
}

Peace of cake!!! Just remember Hummer weight and description

Fine. US army, as all armies in the world wish equip cars with shield and gun! A lot of money for us! Lets do it:

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer() { }

 public int Weight
 {
  get { return 5000; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public class CarShield : IArmyCar
{
 public CarShield() { }

 public int Weight
 {
  get { return 6000; }
 }

 public string Description
 {
  get { return "Hummer car + shield"; }
 }
}

public class CarArmor : IArmyCar
{
 public CarArmor() { }

 public int Weight
 {
  get { return 5200; }
 }

 public string Description
 {
  get { return "Hummer car + MAG"; }
 }
}

public class CarExtraLights : IArmyCar
{
 public CarExtraLights() { }

 public int Weight
 {
  get { return 5020; }
 }

 public string Description
 {
  get { return "Hummer car + strong lights"; }
 }
}

public class CarExtraAccumulator : IArmyCar
{
 public CarExtraAccumulator() { }

 public int Weight
 {
  get { return 5100; }
 }

 public string Description
 {
  get { return "Hummer car + big accumulator"; }
 }
}

Very good!

We are great company and we recruited new mechanical engineer, which make H1 stronger and lighter! Great success!!! But... now i need recalculate all Weight fields from all classes... OK, lets do it. Now H1 weight is 4500 kg:


public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer () { }

 public int Weight
 {
  get { return 4500; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public class CarShield : IArmyCar
{
 public CarShield() { }

 public int Weight
 {
  get { return 5500; }
 }

 public string Description
 {
  get { return "Hummer car + shield"; }
 }
}

public class CarArmor : IArmyCar
{
 public CarArmor() { }

 public int Weight
 {
  get { return 4700; }
 }

 public string Description
 {
  get { return "Hummer car + MAG"; }
 }
}

public class CarExtraLights : IArmyCar
{
 public CarExtraLights() { }

 public int Weight
 {
  get { return 4520; }
 }

 public string Description
 {
  get { return "Hummer car + strong lights"; }
 }
}

public class CarExtraAccumulator : IArmyCar
{
 public CarExtraAccumulator() { }

 public int Weight
 {
  get { return 4600; }
 }

 public string Description
 {
  get { return "Hummer car + big accumulator"; }
 }
}

Of course, we violate Open close principle, but for a now it is all changes.

After 3 month France army wish buy 10000 Hummers, equipped with extra accumulator and strong lights. OK... it is a lot of money!
Lets add CarExtraAccumulatorExtraLights class:

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer () { }

 public int Weight
 {
  get { return 4500; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public class CarShield : IArmyCar
{
 public CarShield() { }

 public int Weight
 {
  get { return 5500; }
 }

 public string Description
 {
  get { return "Hummer car + shield"; }
 }
}

public class CarArmor : IArmyCar
{
 public CarArmor() { }

 public int Weight
 {
  get { return 4700; }
 }

 public string Description
 {
  get { return "Hummer car + MAG"; }
 }
}

public class CarExtraLights : IArmyCar
{
 public CarExtraLights() { }

 public int Weight
 {
  get { return 4520; }
 }

 public string Description
 {
  get { return "Hummer car + strong lights"; }
 }
}

public class CarExtraAccumulator : IArmyCar
{
 public CarExtraAccumulator() { }

 public int Weight
 {
  get { return 4600; }
 }

 public string Description
 {
  get { return "Hummer car + big accumulator"; }
 }
}

public class CarExtraAccumulatorExtraLights : IArmyCar
{
 public CarExtraAccumulator() { }

 public int Weight
 {
  get { return 4500 + 100 + 20; }
 }

 public string Description
 {
  get { return "Hummer car + big accumulator + strong lights"; }
 }
}

Looks no bad. But we need remember H1 weight, accumulator weight, lights weight.

After 2 weeks H1 weight changed, accumulator weight changed but lights weight do not. After month some country wish buy H1 + armor. After 2 months other country wish H1 + Lights+ armor.
After 1 year we have 1000 classes, because some countries wish 3 guns and 6 accumulators on H1!!!! Oh my god! And after 2 years we have 20000 classes...


And after all H1 weight changed again... 
I quit! No more! I started take anti-anxiety medication and it helps me.

But, fortunately i find time-machine !!!!

And i go back in the time to learn patterns and change H1 project!

From http://www.dofactory.com i read: "Decorators provide a flexible alternative to subclassing for extending functionality".

It is exactly what i need! Change behaviour of object on the fly!

After 2 hours of programming i got it!

public interface IArmyCar
{
 int Weight { get; }
 string Description { get; }
}

public class Hummer : IArmyCar
{
 public Hummer () { }

 public int Weight
 {
  get { return 5000; }
 }

 public string Description
 {
  get { return "Hummer car"; }
 }
}

public abstract class CarDecorator : IArmyCar
{
 protected int _weight;
 protected string _description;

 public int Weight
 {
  get { return _weight; }
 }

 public string Description
 {
  get { return _description; }
 }
}

public class CarShield : CarDecorator
{
 public CarShield(IArmyCar ac)
 {
  _weight = 1000 + ac.Weight;
  _description = ac.Description + " + shield";
 }
}

public class CarArmor : CarDecorator
{
 public CarArmor(IArmyCar ac)
 {
  _weight = 200 + ac.Weight;
  _description = ac.Description + " + MAG";
 }
}

public class CarExtraLights : CarDecorator
{
 public CarExtraLights(IArmyCar ac)
 {
  _weight = 20 + ac.Weight;
  _description = ac.Description + " + strong lights";
 }
}

public class CarExtraAccumulator : CarDecorator
{
 public CarExtraAccumulator(IArmyCar ac)
 {
  _weight = 100 + ac.Weight;
  _description = ac.Description + " + big accumulator";
 }
}

And using... We use it like build cabbage in our self: adding layer by layer, layer by layer.
Lets create H1with 3 accumulators and 3 guns:

IArmyCar ac = new Hummer();
Console.WriteLine("Weight: {0}, description: {1}", ac.Weight, ac.Description);

ac = new CarArmor(new CarArmor(new CarArmor(
 new CarExtraAccumulator(new CarExtraAccumulator(new CarExtraAccumulator(new Hummer()))))));
Console.WriteLine("Weight: {0}, description: {1}", ac.Weight, ac.Description);

Output:
Weight: 5000, description: Hummer car
Weight: 5900, description: Hummer car + big accumulator + big accumulator + big accumulator + MAG + MAG + MAG

Press any key to continue . . .

Moreover, i do not need care about changes in weight of other parts! If, for example, weight of accumulator changed, it not influence on other classes!!! All decorators are phlegmatic to each other!!!
That's all.