I have 3 WinForm controls, each of which have the same functionality...
a) load data to a datagridview
b) approve data
c) run report
I want to build this with OOP in mind. I am beginning to learn OOP and to implement it into my applications.
1) Create Abstract control class that contains below abstract methods...
- LoadData()
- ApproveData()
- RunReport()
and properties...
- UserID
- PeriodRunDate
2) Create a control subclass for each of the 3 controls and implement the abstract class
3) add custom code for each of these methods
4) load these subclass controls in a Client WinForm, and call methods from client form.
Below is my code to date. Am I on the correct path? How do I use the abstract properties in the client form and subclasses?
// Abstract Class Control code...
public partial class AbstractUserControl : UserControl
{
protected abstract string userID { get; }
protected abstract string periodRunDate { get; }
protected abstract void LoadData(DoWorkEventArgs doWorkEventArgs);
protected abstract void DataLoaded(RunWorkerCompletedEventArgs runWorkerCompletedEventArgs);
protected abstract void ApproveData();
protected abstract void RunReport();
public void LoadDataButton_Click(object sender, System.EventArgs eventArgs)
{
this._uiLoadDataBackgroundWorker.RunWorkerAsync();
}
private void _uiLoadDataBackgroundWorker_DoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
this.LoadData(doWorkEventArgs);
}
private void _uiLoadDataBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
this.DataLoaded(runWorkerCompletedEventArgs);
}
}
// first subclass usercontrol
public partial class DetailsUserControl : UserControl
{
private DataSet.DataTable DataTable;
protected override void LoadData(DoWorkEventArgs doWorkEventArgs)
{
DataSetTableAdapters.DataTableAdapter
dataTableAdapter = new DataSetTableAdapters.DataTableAdapter();
this.DataTable = new DataSet.DataTable();
DataTableAdapter.FillData(this.DataTable, userID, periodRunDate);
}
protected override void DataLoaded(RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
this.bindingSource.DataSource = this.DataTable;
}
protected override void ApproveData()
{
// check each row ticked in the datagridview
// and update record in database
}
}
// Client WinForm that loads UserControl(s); Uses RunButton click event
// to call LoadButton Click in subclass controls...
private AbstractUserControl abstractUserControl;
private void RunButton_Click(object sender, EventArgs e)
{
// bind to load data button click event in abstract class
this.LoadDataButton.Click += this.abstractUserControl.LoadDataButton_Click;
}
Although the approach of having a base class that is inherited is a perfectly good one, it unfortunately does not play well with the Windows Forms designer. So if your intention is to double click the class file and then use the Form designer to drag and drop etc. then it will not work. Instead I would recommend the following alternative pattern.
Create a standard UserControl and then you can design it using the Form designer as per usual. This one control will be used for all three related scenarios you have. Then create a base class with three derived classes that implement the business logic you need.
Add a property or method to the UserControl that allows you to inject the business logic instance into the control. The control then calls the exposed abstract methods/properties of the instance. So you have a single user interface control that has a business logic instance injected to determine the essence of the processing performed.
Related
How do you perform property injection with Simple Injector.
The with Ninject you do is as per bellow:
[Inject]
public IUnitOfWork UnitOfWork { get; set; }
How can I do the equivalent to this with Simple Injector. I tried finding a solution online but had no luck.
Why do I want to use Property Injection?
I want to use property injection to set up unit of work in my base controller so that it will create a new unit of work OnActionExecuting and commit the changes OnResultExecuted. It also means I don't have to pass in the UoW with each new controller I create through the constructor.
Another option is to use the RegisterInitializer method:
container.RegisterInitializer<BaseControllerType>(controller =>
{
controller.UnitOfWork = container.GetInstance<IUnitOfWork>();
}
It keeps all configuration in your composition root and does not pollute your code base with all kinds of attributes.
Update: (as promised)
While this is a direct answer to your question I have to provide you with a better option, because the usage of a base class for this is a IMO not the correct design, for multiple reasons.
Abstract classes can become real PITA classes as they tend to grow towards a god class which has all kinds of cross cutting concerns
An abstract class, especially when used with property injection, hides the needed dependencies.
With focus on point 2. When you want to unit test a controller which inherits from the base controller, you have no way of knowing that this controller is dependent on IUnitOfWork. This you could solve by using constructor injection instead of property injection:
protected abstract class BaseController : Controller
{
protected readonly IUnitOfWork uoW;
protected BaseController (IUnitOfWork uoW)
{
this.uoW = uoW;
}
}
public class SomeController : BaseController
{
public SomeController(IUnitOfWork uoW) : base(uoW) { }
}
While this solves point 2, point 1 is still lurking. The main reason you're wanting this, as you say, is because you do not want to commit your changes in every Action method. Changes must just be saved by the context when the request is done. And thinking about design in this way is a good thing, because Saving changes is, or can be seen as a cross cutting concern and the way you're implementing this is more or less known as AOP.
If it's comes to AOP, especially if you're working with atomic actions in the action methods of your controllers, there is a far better, more SOLID and more flexible design possible which deals with this very nicely.
I'm referring to the Command/Handler pattern which is described in great detail here (also read this for the query part of your application).
With this patterns you don't inject a generic IUnitOfWork abstraction, but inject the specific needed ICommandHandler<TCommand> abstractions.
The action methods would fire the responsible commandhandler for this specific action. All commandhandlers can simple be decorated by a single open-generic SaveChangesCommandHandlerDecorator, 'ValidationDecorator', 'CheckPermissionsDecorator', etc...
A quick example:
public class MoveCustomerCommand
{
public int CustomerId;
public Address NewAddress;
}
public class MoveCustomerCommandHandler : ICommandHandler<MoveCustomerCommand>
{
public void Handle(MoveCustomerCommand command)
{
// retrieve customer from database
// change address
}
}
public class SaveChangesCommandHandlerDecorator<TCommand> : ICommandHandler<TCommand>
{
private readonly ICommandHandler<TCommand> decoratee;
private readonly DbContext db;
public SaveChangesCommandHandlerDecorator(
ICommandHandler<TCommand> decoratee, DbContext db)
{
this.decoratee = decoratee;
this.db = db;
}
public void Handle(TCommand command)
{
this.decoratee.Handle(command);
this.db.SaveChanges();
}
}
// Register as
container.Register(typeof(ICommandHandler<>), new []{Assembly.GetExecutingAssembly() });
container.RegisterDecorator(typeof(ICommandHandler<>),
typeof(SaveChangesCommandHandlerDecorator<>));
// And use in controller as
public ActionResult MoveCustomer(int customerId, Address address)
{
var command = new MoveCustomerCommand
{ CustomerId = customerId, Address = address };
this.commandHandler.Handle(command);
return View(new ResultModel());
}
This keeps your controllers clean and let it do what it must do, namely be the layer between the business logic (the commandhandler implementation in this case) and the view.
Need to create the following:
First create the attribute class
[System.AttributeUsage(System.AttributeTargets.Property]
public class Inject : Attribute
{
}
Then create a custom property behavior
class PropertySelectionBehavior<TAttribute> : IPropertySelectionBehavior
where TAttribute : Attribute
{
public bool SelectProperty(Type type, PropertyInfo prop)
{
return prop.GetCustomAttributes(typeof(TAttribute)).Any();
}
}
Finally tell the container to use custom behavior
container.Options.PropertySelectionBehavior = new PropertySelectionBehavior<Inject>();
All that is left to do is decorate the property with the attribute
[Inject]
public IUnitOfWork UnitOfWork { get; set; }
Suppose I have a game, where there are buildings sorted by type. Each type is represented as a separate class, but sometimes I have to do some uncommon logic for the buildings of the same type. How could one implement this kind of behaviour?
For example, I can identify buildings by ID, so I can have a giant switch or command pattern inside the building type class. But I think that something is not right with this approach.
Another approach is to have different class for any divergent logic. But this proposes a lot of small classes.
This is what polymorphism aims to solve, and one of the big differences between procedural and oop programming. You can achieve it through extending a base class, or by implementing an interface. Here is extending a base class:
public abstract class Building {
abstract void destroy();
}
public BrickBuilding extends Building {
#Override
public void destroy() {
bricks.fallToGround();
}
}
public HayBuilding extends Building {
#Override
public void destroy() {
straw.blowInWind();
}
}
In places in your code where you would have used a switch statement to switch on building type, just hold a reference to the abstract Building type, and call method destroy() on it:
public class BuildingDestroyer {
public void rampage() {
for(Building building : allTheBuildings) {
// Could be a BrickBuilding, or a HayBuilding
building.destroy();
}
}
}
Or, to address your concern about having a lot of small types, you can 'inject' a destroy behaviour you want into a common building type, like so...albeing, you will end up with a lot of different destroy behaviour classes too...so, this might not be a solution.
public interface DestroyBehaviour {
void destroy(Building building);
}
public class Building {
private int id;
public DestroyBehaviour destroyBehaviour;
public Building(int id, DestroyBehaviour destroyBehaviour) {
this.id = id;
this.destroyBehaviour = destroyBehaviour;
}
public void destroy() {
destroyBehaviour.destroy(this); // or something along those lines;
}
}
You can get rid of the giant switch by having a BuildingFactory class which exposes a registerBuildingType(typeName, instanceCreatorFunc) method, that each building class calls (from a static initialize method for example) and that gets called with a unique string for that class (class name would suffice) and a static "create" method that returns a new instance.
This approach also has the advantage of being able to load new buildings from dynamically linked libraries.
i have a question regarding design patterns.
suppose i want to design pig killing factory
so the ways will be
1) catch pig
2)clean pig
3) kill pig
now since these pigs are supplied to me by a truck driver
now if want to design an application how should i proceed
what i have done is
public class killer{
private Pig pig ;
public void catchPig(){ //do something };
public void cleanPig(){ };
public void killPig(){};
}
now iam thing since i know that the steps will be called in catchPig--->cleanPig---->KillPig manner so i should have an abstract class containing these methods and an execute method calling all these 3 methods.
but i can not have instance of abstract class so i am confused how to implement this.
remenber i have to execute this process for all the pigs that comes in truck.
so my question is what design should i select and which design pattern is best to solve such problems .
I would suggest a different approach than what was suggested here before.
I would do something like this:
public abstract class Killer {
protected Pig pig;
protected abstract void catchPig();
protected abstract void cleanPig();
protected abstract void killPig();
public void executeKillPig {
catchPig();
cleanPig();
killPig();
}
}
Each kill will extend Killer class and will have to implement the abstract methods. The executeKillPig() is the same for every sub-class and will always be performed in the order you wanted catch->clean->kill. The abstract methods are protected because they're the inner implementation of the public executeKillPig.
This extends Avi's answer and addresses the comments.
The points of the code:
abstract base class to emphasize IS A relationships
Template pattern to ensure the steps are in the right order
Strategy Pattern - an abstract class is as much a interface (little "i") as much as a Interface (capital "I") is.
Extend the base and not use an interface.
No coupling of concrete classes. Coupling is not an issue of abstract vs interface but rather good design.
public abstract Animal {
public abstract bool Escape(){}
public abstract string SaySomething(){}
}
public Wabbit : Animal {
public override bool Escape() {//wabbit hopping frantically }
public override string SaySomething() { return #"What's Up Doc?"; }
}
public abstract class Killer {
protected Animal food;
protected abstract void Catch(){}
protected abstract void Kill(){}
protected abstract void Clean(){}
protected abstract string Lure(){}
// this method defines the process: the methods and the order of
// those calls. Exactly how to do each individual step is left up to sub classes.
// Even if you define a "PigKiller" interface we need this method
// ** in the base class ** to make sure all Killer's do it right.
// This method is the template (pattern) for subclasses.
protected void FeedTheFamily(Animal somethingTasty) {
food = somethingTasty;
Catch();
Kill();
Clean();
}
}
public class WabbitHunter : Killer {
protected override Catch() { //wabbit catching technique }
protected override Kill() { //wabbit killing technique }
protected override Clean() { //wabbit cleaning technique }
protected override Lure() { return "Come here you wascuhwy wabbit!"; }
}
// client code ********************
public class AHuntingWeWillGo {
Killer hunter;
Animal prey;
public AHuntingWeWillGo (Killer aHunter, Animal aAnimal) {
hunter = aHunter;
prey = aAnimal;
}
public void Hunt() {
if ( !prey.Escape() ) hunter.FeedTheFamily(prey)
}
}
public static void main () {
// look, ma! no coupling. Because we pass in our objects vice
// new them up inside the using classes
Killer ElmerFudd = new WabbitHunter();
Animal BugsBunny = new Wabbit();
AHuntingWeWillGo safari = new AHuntingWeWillGo( ElmerFudd, BugsBunny );
safari.Hunt();
}
The problem you are facing refer to part of OOP called polymorphism
Instead of abstract class i will be using a interface, the difference between interface an abstract class is that interface have only method descriptors, a abstract class can have also method with implementation.
public interface InterfaceOfPigKiller {
void catchPig();
void cleanPig();
void killPig();
}
In the abstract class we implement two of three available methods, because we assume that those operation are common for every future type that will inherit form our class.
public abstract class AbstractPigKiller implements InterfaceOfPigKiller{
private Ping pig;
public void catchPig() {
//the logic of catching pigs.
}
public void cleanPig() {
// the logic of pig cleaning.
}
}
Now we will create two new classes:
AnimalKiller - The person responsible for pig death.
AnimalSaver - The person responsible for pig release.
public class AnimalKiller extends AbstractPigKiller {
public void killPig() {
// The killing operation
}
}
public class AnimalSaver extends AbstractPigKiller {
public void killPing() {
// The operation that will make pig free
}
}
As we have our structure lets see how it will work.
First the method that will execute the sequence:
public void doTheRequiredOperation(InterfaceOfPigKiller killer) {
killer.catchPig();
killer.cleanPig();
killer.killPig();
}
As we see in the parameter we do not use class AnimalKiller or AnimalSever. Instead of that we have the interface. Thank to this operation we can operate on any class that implement used interface.
Example 1:
public void test() {
AnimalKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `AnimalKilleraKiller `
AnimalSaver aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
Example 2:
public void test() {
InterfaceOfPigKiller aKiller = new AnimalKiller();// We create new instance of class AnimalKiller and assign to variable aKiller with is type of `InterfaceOfPigKiller `
InterfaceOfPigKiller aSaver = new AnimalSaver(); //
doTheRequiredOperation(aKiller);
doTheRequiredOperation(aSaver);
}
The code example 1 and 2 are equally in scope of method doTheRequiredOperation. The difference is that in we assign once type to type and in the second we assign type to interface.
Conclusion
We can not create new object of abstract class or interface but we can assign object to interface or class type.
I have a working .net winform user control and would like to convert it to COM. I've been struggling finding a way to convert this user control to be COM enabled (for use in VS6/C++6). I'm not sure if this is do-able? Or I have to think about a different approach? Here's the interface:
[ComVisible(true)]
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("C8BDB591-189D-4EB5-A026-7C9FFBEE3A85")]
public interface iMainInterface
{
[DispId(1)]
void ShowMyInterface();
}
And here's the control:
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[ComSourceInterfaces(typeof(iMainInterface))]
[Guid("F8D26781-5A97-4467-B732-7EAB1A04C3F2")]
public partial class MainInterface : UserControl
{
public void ShowMyInterface()
{
...
}
}
The error message seems to be for [ComSourceInterfaces(typeof(iMainInterface))]
Here's the error:
Error 2 Cannot register assembly "MyInterface.dll". Type 'xxx.MainInterface' does not support the specified default COM interface: 'xxx.iMainInterface' PerformReportControl
[ComSourceInterfaces] should only be used for interfaces that generate events. It sure doesn't look like iMainInterface has any events so just remove the attribute.
You forgot to have your class inherit the interface. Fix:
[ComVisible(true)]
[ClassInterface(ClassInterfaceType.None)]
[Guid("F8D26781-5A97-4467-B732-7EAB1A04C3F2")]
public partial class MainInterface : UserControl, iMainInterface
{
public void ShowMyInterface()
{
...
}
}
Do favor a capital I (not i) for interface types.
I've got a RIA silverlight 4 app with a complex data type as a model. As a familiar example let's call it aspnet_User which has a member object called aspnet_Membership; aspnet_User has a member called "UserName" and aspnet_Membership has a member called "Email". Now using the aspnet_User as a datacontext I want to bind to any changes in aspnet_User or an attached aspnet_Membership - i.e. I want to show if an aspnet_User is 'dirty'. The dirty flag should show if I change either aspnet_User.UserName or aspnet_Membership.Email. Now previously I have implemented a Converter and bound to the EntityState on an object, and this is fine for showing whether simple properties are dirty but EntityState is not altered when aspects of aspnet_Membership member are edited.
I have tried to implement a property called BubbledEntityState which reflects a modified EntityState on either aspnet_User or aspnet_membership. It is defined in a partial class in the Silverlight project. This needs to react to EntityState PropertyChanged events on aspnet_User or it's member aspnet_Membership. So I've tried to handle these events in the partial OnCreated method. Strangely however this isn't getting called at all. Here is the method:
public partial class aspnet_User
{
partial void OnCreated()
{
this.aspnet_Membership.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(aspnet_Membership_PropertyChanged);
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(aspnet_User_PropertyChanged);
}
...
}
I'm presuming aspnet_User objects are constructed on the server and are not 'reconstructed' when they are reconstituted on the client after RIA has done it's WCF call. This strikes me as peculiar. Am I doing something cranky? Anyone got a better way of dealing with this?
OK I've got this working. It still seems a bit convoluted, but rather than using the OnCreated partial method I've overloaded the OnLoaded method:
protected override void OnLoaded(bool isInitialLoad)
{
base.OnLoaded(isInitialLoad);
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(aspnet_User_PropertyChanged);
}
partial void OnCreated()
{
}
void aspnet_User_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "aspnet_Membership")
{
if (this.aspnet_Membership != null)
{
this.aspnet_Membership.PropertyChanged+=new System.ComponentModel.PropertyChangedEventHandler(aspnet_Membership_PropertyChanged);
}
}
if (e.PropertyName == "EntityState")
this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("BubbledEntityState"));
}
void aspnet_Membership_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "EntityState")
this.OnPropertyChanged(new System.ComponentModel.PropertyChangedEventArgs("BubbledEntityState"));
}
public EntityState BubbledEntityState
{
get
{
if (this.EntityState== System.Windows.Ria.EntityState.Unmodified)
{
if (this.aspnet_Membership==null)
return System.Windows.Ria.EntityState.Unmodified;
if (this.aspnet_Membership.EntityState== System.Windows.Ria.EntityState.Modified)
return System.Windows.Ria.EntityState.Modified;
return System.Windows.Ria.EntityState.Unmodified;
}
return this.EntityState;
}
}