Design issue in a MVP win forms application - c#

In a module of a win forms application I have a hierarchy of classes like BaseRecovery, LoanRecovery and FineRecovery. Both LoanRecovery and FineRecovery inherits from BaseRecovery. All these models have one view called RecoveryForm where you can enter/view loans and fines of employees. and I'm planing to use single Presenter class called RecoveryPresenter which inherits from BasePresenter. We have a DataService Class for db transactions
LoanRecovery class looks like this...
Class LoanRecovery : BaseRecovery
{
public string LoanID {get;set;}
public DateTime IssueDate {get;set;}
public Decimal Amount {get;set;}
.
.
.
}
So I'd do the following in Programe.cs.
IBaseRcovery recovery=null;
IRecoveryForm recoveryForm = new RecoveryForm();
IDataService dataService = new DataService();
BasePresenter presenter = new RecoveryPresenter( recovery, recoveryForm, dataService );
presenter.Show(); // This will display the form recoveryForm
In the presenter I would say
public RecoveryPresenter( IBaseRecover model, IRecoveryForm view, IDataService dataService )
{
this._Model = model;
this._View = view;
this._DataService = dataService;
WireUpViewEvents();
}
Now lets say if I need to give a loan, I would run SetModelPropertisFromView() mehtod in the BasePresenter class which use reflection. But before that I should pass an instance of LoanRecovery class (i.e. _Model) to that method together with _View. Like wise we can do same thing for all children classes as follows...
public void Issue()
{
if (_View.Type == "Loan")
{
_Model = new LoanRecovery();
SetModelPropertiesFromView(_Model, _View, _DataService);
_dataService.InsertLoan(_Model); //Error
}
if (_View.Type == "Fine")
{
_Model = new FineRecovery();
SetModelPropertiesFromView(_Model, _View, _DataService);
_DataService.InsertFine(_Model); //Error
}
if (_View.Type == "Insurance")
{
_Model = new InsuranceRecovery();
SetModelPropertiesFromView(_Model, _View, _DataService);
_DataService.InsertFine(_Model); //Error
}
}
Everything fine until the last line of the above if blocks. The issue is data access method in the DataService class required a child instance not a base class instance.
public void InsertLoan( LoanRecovery loan)
{
using (SqlConnection sqlConnection = new SqlConnection(db.GetConnectionString))
{
SqlCommand sqlCommand = new SqlCommand("BEGIN INSERT INTO recovery ;
sqlCommand.Parameters.Add("#empID", SqlDbType.Char).Value = loan.EmployeeID;
sqlCommand.Parameters.Add("#loanType", SqlDbType.VarChar).Value = loan.Type;
sqlCommand.Parameters.Add("#loanAmount", SqlDbType.Decimal).Value = loan.FullAmount;
sqlCommand.Parameters.Add("#loanDuration", SqlDbType.Int).Value = loan.Duration;
sqlConnection.Open();
sqlCommand.ExecuteNonQuery();
}
}
So I solved the problem as follows...
public void Issue()
{
if (_View.Type == "Loan")
{
LoanRecovery loanModel = new LoanRecovery(); //Creates a child instance
SetModelPropertiesFromView(loanModel, _View, _DataService);
_DataService.InsertLoan(loanModel);
}
}
Now its working but my worry is that here I'm not using the injected instance through the constructor rather newing a child object which creates a dependency. Can anybody propose a better design to solve this issue please?

OK, if I understand correctly, your IDataService interface has specific methods for saving your concrete classes that implement IBaseRecover, but to call the correct save method, you need to know the concrete type of IBaseRecover. Why not push the save responsibility into the concrete implementations of IBaseRecover because they know best which method should be called. You could do this like follows:
interface IBaseRecover{
void Save();
....
}
class LoanRecovery : IBaseRecover {
private IDataService _dataService;
LoadRecovery(IDataService dataService){
_dataService = dataService;
}}
void Save(){
_dataService.InsertLoan(this);
}
}
OK, here's another thought based on your comment. I think the complexity here comes from the fact that you are using a view that can represent three different types of models, and even though they all derive from the same base class, your view has inputs that are specific to each implementation. That's fine, but I think you'd benefit from a different variation of the MVP pattern. Martin Fowler has since broken up the MVP pattern into Supervising Contoller and Passive View. I think Passive View would serve you well here. In that case, your view would expose the values of it's input elements as properties so that the Presenter could get Recovery properties such as IssueDate and Amount without have to know about the view components. So the code for the Insert Action on the view might look something like the following:
public decimal Amount{
get{
return Convert.ToDecimal(txtAmount.text);
}
}
void btnInsert_Click(Object sender, EventArgs e){
presenter.Insert();
}
Note that it's ok for your view to have an instance of the Presenter. Now the Presenter Insert method might look something like this:
public void Insert(){
if(_view.Type == "Loan"){
var model = new LoadRecovery();
model.IssueDate = _view.IssueDate;
model.Amount = _view.Amount;
_dataService.InsertLoan(model);
}
}
And if you were also first displaying a Recovery to be updated instead of inserted:
public void Show(){
_view.IssueDate = model.IssueDate;
_view.Amount = model.Amount;
}

Related

Generic class constraint where <T> is a type constraining the generic class

Perhaps not the most accurate title, but it's a little difficult to describe; perhaps you guys can help me out here? I'm writing a game using the MVC format, and I want each base class (controller, model, and view) to have a reference to their accompanying features, forming a sort of triangle (ie. A model has a reference to a controller that defines it, and a view that references it, etc. ) Much of these classes look like this:
public class Model {
public Controller controller;
public View view;
public void Connect (Controller controller, View view) {
this.controller = controller;
this.view = view;
}
}
This is okay, but whenever I intend to pull up a ChildModel's controller, I'll need to cast to the appropriate ChildController to obtain the correct version. I could make a utility method/getter to fetch an appropriately cast item, but I'd rather not rewrite this piece of code for each and every child class. I thought I could solve this issue by making the base classes generic, but now I'm running into an issue where the newly generic classes need references to the class that's trying to define them, hence:
public class Model<V, C> where V : View<?, C> where C : Controller<?, V> {
public Controller<?, V> controller;
public View<?, C> view;
public void Connect (Controller<?, V> controller, View<?, C> view) {
this.controller = controller;
this.view = view;
}
}
As you can see, this quickly gets messy in the base class. I don't know what symbol to place for (in reference to the example above) the Model that's attempting to define the constraints. Placing 'Model' into the question marks doesn't seem to compile either, as I run into a hellish boxing conversion issue.
Is there a way to accomplish what I'm after, or am I just trying to be too clever here? If this could work, I'd love to be able to declare child classes with the type constrained to their 'triangle', thus I could avoid needless casting or helper methods:
public class ChildModel<ChildView, ChildController> {
public ChildModel () {
this.controller <- calls ChildController type, not base type!
}
}
Anyone have any ideas?
It looks like you are confusing ownership with interactions. Ownership implies that one owns the other, while interactions imply how they communicate with one another. MVC primarily defines interactions between the three participants, though you could say that a view and controller both own a model.
In your code as shown, a class owns a property, therefore a controller class owns a view and a view owns a controller.
var model = new Model();
var view = new View<Controller<Model, View<Controller, Model>, ...
This doesn't work with generics in the way you would like because the interactions become circular. It is the chicken and the egg problem: chickens come from eggs which are laid by chickens. We can solve most of the problem by giving the controller ownership of the view, and both the controller and view ownership of a model.
public class Model
{
}
public interface IView<M>
{
M Model { get; }
}
public class MyView : IView<Model>
{
public MyView(Model model)
{
Model = model;
}
public Model Model
{
get;
}
}
public interface IController<V, M>
{
M Model { get; }
V View { get; }
}
public class MyController : IController<MyView, Model>
{
public MyController(MyView view, Model model)
{
View = view;
Model = model;
}
public Model Model
{
get;
}
public MyView View
{
get;
}
}
We still used generics to do this, and you have easy access to most of the information so far without introducing circular references.
class Program
{
public static void Main()
{
var model = new Model();
var view = new MyView(model);
var controller = new MyController(view, model);
}
}
Now if you want to make sure the view has a reference to the controller, you can do this via a property.
view.Controller = controller;
You could disregard everything I just showed you - and go the property injection route. This means instead of taking in the dependencies by the constructor, which creates circular reference restrictions on how the objects can be created, you can simply do this.
var model = new Model();
var view = new View();
var controller = new Controller();
model.View = view;
model.Controller = controller;
view.Controller = controller;
view.Model = model;
controller.View = view;
controller.Model = model;
Whatever method you use, the trick is to avoid the circular dependency issue that you have in your current code. Most MVC frameworks provide rich data binding which breaks the direct coupling between the classes, but if you don't have that, you have to either write something or find something, or work within the confinements of the language rules.
There are a lot of ways to solve this. As I wrote this there was another answer posted so you should also look at that.
Here's my suggestion.
1. You should use the Controller as the main part of your MVC pattern. The controller should get the information from the Mode, process it and then call the view.
Here's my base class for the Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance.Classes
{
public class Controller<T, U> where T : Model, new() where U : View, new()
{
protected T _model;
protected U _view;
public Controller()
{
this._model = new T();
this._view = new U();
}
public Controller(T model, U view)
{
this._model = model;
this._view = view;
}
public string ParentFunction()
{
return "I'm the parent";
}
}
}
Note, I have also a Model and View base class. Since they are empty for the moment, I won't show you the code
Then, I can define my child classes. For example, I will make a PageController, PageModel and PageView. They will all inherite from their BaseClass.
Note : Once again, PageModel and PageView are empty. They are only used for the inheritance
PageController.cs
using Inheritance.Page;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Inheritance.Classes
{
public class PageController : Controller<PageModel, PageView>
{
public PageController():base()
{
}
public PageModel Model
{
get
{
return base._model;
}
}
}
}
So as you can see, you will specify the Model class and the View class only inside the PageController.
To use your classes, you can do as follow :
PageController controller = new PageController();
//We can access the parent function
Console.WriteLine(controller.ParentFunction());
//Function defined into the controller.
PageModel model = controller.Model;
I think this is what you want:
public class GameModel : Model
{
public int ID { get; set; }
}
public class GameView : View<GameModel, GameView>
{
public float FOV { get; set; }
}
public class GameController : GameView.BaseControler
{
// Set ID
public GameController()
{
Model.ID=100;
View.FOV=45f;
}
}
class Program
{
static void Main(string[] args)
{
var gm = new GameModel();
var view = new GameView();
var ctrl = new GameController();
view.Connect(gm, ctrl);
Debug.WriteLine(view.Model.ID);
}
}
public class Model
{
}
public class View<TModel,TView> where TModel : Model where TView : View<TModel, TView>
{
public TModel Model { get; private set; }
public BaseControler Controler { get; private set; }
public void Connect(TModel model, BaseControler controler)
{
this.Model=model;
this.Controler=controler;
this.Controler.Connect(model, this as TView);
}
public class BaseControler
{
public TView View { get; private set; }
public TModel Model { get; private set; }
public void Connect(TModel model, TView view)
{
this.Model=model;
this.View=view;
}
}
}

how to minimize dependency between a form and a class in C#

In this sample code (C# winForms app) there is a Employee class with SearchEmployee() method and a DataService class with GetByEmployeeID() method. When searching for a employee, SearchEmployee() method will call GetByEmployeeID() method to talk to database. I have minimized the dependency between Employee class and DataService class by using constructor injection. (in its simplest way with out using an Interface)
But there is a dependency between Form class and Employee class as I new employee object from From class.
Will that dependency be a problem or isn't?
If that dependency should be avoided, What is the simplest way to achieve this?
I prefer not to use a pattern like MVP as I'm not familiar with it.
Class Form
{
public Form()
{
InitializeComponents();
}
private void btnSave_Click(object sender, EventArgs e)
{
Employee newEmp = new Employee (new DataService()); //Making a dependency
newEmp = newEmp.SearchEmployee (txtEmployeeID.Text);
txtEmployeeName.Text = newEmp.EmployeeName;
txtEmployeeAddress.Text = newEmp.EmployeeAddress;
}
}
Class Employee
{
string EmployeeID { get; set; }
string EmployeeName { get; set; }
string EmployeeAddress { get; set; }
DataService _DS;
public Employee(DataService DS) //Constructor injection of dataservice object
{
this._DS = DS;
}
public Employee SearchEmployee (string employeeID)
{
this.EmployeeID =employeeID;
DataTable DT= _DS.GetByEmployeeID(EmployeeID);
this.EmployeeName = DT.Rows[0].ItemArray[1].ToString();
this.EmployeeAddress = DT.Rows[0].ItemArray[2].ToString();
return this; //Returning an employee object to the caller
}
}
//This class responsible for database transaction
class DataService
{
public DataTable GetByEmployeeID(string employeeID)
{
using (SqlConnection newCon = new SqlConnection(db.GetConnectionString))
{
SqlCommand Cmd = new SqlCommand("SELECT..WHERE emp_id=#employeeID", newCon);
Cmd.Parameters.Add("#employeeID", SqlDbType.varChar).Value = employeeID;
newCon.Open();
SqlDataReader rdr = Cmd.ExecuteReader();
DataTable results = new DataTable();
results.Load(rdr);
return results;
}
}
}
Actually, a class representing an entity should contain information relevant to that entity.
Any method that belong to the management of the entity, like looking for a specific object, telling which ones contain a set of properties and the like should be in a different class.
To make my point clear:
You can have your "Employee" with only the 3 string properties and then an "EmployeeManager" which is responsible of searching for employees, containing a list with all employees, looking by id, etc.
That way, you objects will be only information carriers and you will brake the dependency between them.
In your case, it makes more sense to have the "SearchEmployee" method on the Data Service.
Will that dependency be a problem or isn't? - It's not a problem here until how you want to get things done.
If that dependency should be avoided..? - Yes. Your program is having only one unit of work which is GetByEmployeeID(string employeeID). Dependency Injection(DI) is supposed to use when an employee object will need some other objects like department(which becomes dependency of employee object & will be injected via constructor pattern). In your program, dependency works like a service so there is almost no possibility that it alters its behavior depending on the caller. Also DI simplifies testing/mocking objects, testing employee object will eliminate the need of testing it's dependencies i.e. department.
What is the simplest way to achieve this?. I prefer not to use a pattern like MVP as I'm not familiar with it. -
Well, simplest requires solid base/architecture, then after your program will be able to accomplish this task in quite a few lines of code. You can use ORM(object relational mapper) frameworks like Microsoft entity framework which simplifies domain/data/repository/unit-of-work part.

C# MVVM: Adding new ViewModel (strict non-exposed Model design)

I've been working on an MVVM application in C# but consistiently run into some problems when working with the collections of ViewModels my View digests. Specifically, they all tend to relate to the issue of the Model being a private member of the ViewModel.
An example of this is creating new ViewModels (as requested by the View). For some preamble (although you might not need these to help me) here are example Model and ViewModel classes:
Private Class Model()
{
public string Name { get; set; }
}
Public Class ViewModel()
{
Private Model _Model;
Public Void ViewModel(Model model)
{
_Model = model;
}
Public String Name
{
get
{
return _Model.Name;
}
set
{
_Model.Name = value;
}
}
}
The entire model is never directly exposed as a public member of the ViewModel. The MainWindowViewModel handles collections of Models (private, the view cant see these) and ViewModels (public for View digestion):
Public Class MainWindowViewModel
{
Private List<Model> _NamesModel;
Private ObservableCollection<ViewModel> _NamesViewModel;
Public Void MainWindowViewModel()
{
//Lets pretend we have a service that returns a list of models
_NamesModel = Service.Request();
foreach(Model model in _NamesModel)
{
ViewModel viewmodel = new ViewModel(model);
_NamesViewModel.Add(viewmodel);
}
}
Public ObservableCollection<ViewModel> NamesViewModel
{
get
{
return _NamesViewModel;
}
}
}
Now thats the preamble but now I have a problem. How do I add a new ViewModel? Do methods within my view create a new ViewModel and populate that? Being a purist, I'm assuming the View should not be allowed to create or populate Models at all. Should my ViewModel contain a constructor that accepts nothing (i.e. no underlying model) and instead creates a blank to populate?
These kinds of issues keep coming up with a "pure" MVVM approach. I've had to create a public method in my ViewModel (bool compare(Model model)) that will compare a model (ready for deletion etc.) to it's internal one. If the models were publicly exposed (breaking purity) then it would be much easier to do stuff like find the ViewModel thats connected to a Model.
I can sympathize with some of those problems. I recently wrote an MVVM application where similar questions came up frequently. One of the tricks is to decide - definitively - which class is going to be responsible for Model instances. Do you want it to be your MainWindowViewModel? Or your NameViewModel? You don't want to share the responsibilities of creating/deleting the model between both of those classes; you'll have quite a logistical nightmare.
Secondly, even a "pure" MVVM approach doesn't dictate that you can't expose the model publicly. You said yourself that doing so would save you a lot of headache: DO IT. MVVM dictates only that the ViewModel has no knowledge/access of the View. There are many "official" MVVM examples that go so far as to implement their Model using the INotifyPropertyChanged interface, and bind directly to properties on the Model.
Personally, I think I would dictate control of the NameModel to the NameViewModel. This means that you should remove the list of NameModels completely from the MainWindowViewModel. If you want to give the NameViewModel an optional constructor which takes a Model, that would be fine too.
I'm a fan of this approach:
public NameViewModel : ViewModelBase
{
public NameModel Model
{
get { /* get stuff */ }
set { /* set stuff */ }
}
// Default constructor creates its own new NameModel
public NameViewModel()
{
this.Model = new NameModel();
}
// Constructor has a specific model dictated to it
public NameViewModel(NameModel model)
{
this.Model = model;
}
//Model wrapper properties
public String Name
{
get { return Model.Name; }
set { Model.Name = value; }
}
}
and...
public class MainWindowViewModel
{
Private ObservableCollection<ViewModel> _NameViewModels;
Public Void MainWindowViewModel()
{
//Lets pretend we have a service that returns a list of models
var nameModels = Service.Request();
foreach(Model model in nameModels)
{
ViewModel viewmodel = new NameViewModel(model);
NameViewModel.Add(viewmodel);
}
}
Public ObservableCollection<ViewModel> NameViewModels
{
get
{
return _NameViewModels;
}
}
}
In this way your MainWindowViewModeldoesn't keep an entirely separate copy of the Models; it only tracks the NameViewModels. Each NameViewModel is responsible for its own underlying model, while still making the option available to have a specific model passed to it during construction.
All the creation-related issues can be resolved with introduction of factory design pattern. The factory will take care of creating view models basing on model that was provided.
public class MainWindowViewModel
{
private List<Model> _NamesModel;
private ObservableCollection<ViewModel> _NamesViewModel;
private IViewModelFactory factory;
public void MainWindowViewModel(IViewModelFactory factory)
{
//Lets pretend we have a service that returns a list of models
_NamesModel = Service.Request();
_NamesViewModel = factory.CreateNamesViewModels(_NamesModel);
}
public ObservableCollection<ViewModel> NamesViewModel
{
get
{
return _NamesViewModel;
}
}
}
What is more, you could even get rid of Service dependency in view model and move it to the factory itself, thus reducing the need to keep model in view model (admittedly though, removal of model might not work in more complex scenarios):
public ObservableCollection<ViewModel> CreateNamesViewModels()
{
var models = Service.Request();
return new ObservableCollection(models.Select(m => new ViewModel(m)));
}
Also, your main window view model can expose commands that utilize factory to create any new instances. This way, no model is leaking to view and also no creation details are exposed (since commands will hide actual implementation).

Injecting dependency into DTO

Introduction
I'm using ASP.Net MVC3. My Controllers talk to a service layer, and the service layer talks to a Data Acces layer which uses Entity Framework.
I get a specific entity using Entity Framework. This entity is converted into a DTO. Then I deliver this DTO to a MVC controller. Something like this:
pseudo code:
// This is inside my Service Layer
var entity = DataAccess.GetById(id);
var dto = createDtoWithValuesFrom(entity);
return dto; // Return dto to MVC controller
In this DTO I would like to use a dependency, to for example a Calculator. Let's say my DTO looks like this:
public class Customer
{
private ICalculator Calculator;
public class Customer(ICalculator calculator)
{
Calculator = calculator;
}
public string Name { get; set; }
public decimal Discount
{
get
{
return Calculator.Discount();
}
}
}
Problem
How do I instanciate my DTO, and let Autofac inject a calculator?
I can think of a way to do this:
var calculator = DependencyResolver.Current.GetService<ICalculator>;
var dto = new DTO(calculator );
But I don't know if this is the best way to do it, since it smells of ServiceLocator, and I've read that it's not prefered to use that.
DTOs normally have some properties and do not contain any logic.
You should consider a design where your MVC-Controller does something like this:
Get the customer from the service/dataaccess
Calculate the discount by invoking the ICalculator which could be passed to the Controller using constructor injection (or call an extra service which does the calculation)
Create a new model class which contains the customer and the calculated discount and pass this model to the view.
public class Model
{
public Customer Customer { get; set; }
public double Discount { get; set; }
}
public class SomeController : Controller
{
private readonly DataAccess dataAccess;
private readonly ICalculator calculator;
public SomeController(DataAccess dataAccess, ICalculator calculator)
{
this.dataAccess = dataAccess;
this.calculator = calculator;
}
public ActionResult Index(int id)
{
var model = new Model();
model.Customer = this.dataAccess.Get(id);
model.Discount = this.calculator.Calculate(customer);
return View(model);
}
}
First of all: A DTO is not a View Model.
A DTO (Data Transfer Object) is a dummy class (it's really not a first class (OOP) citizen). It's purpose is only to flatten hierarchies and transport information between different layers/tiers.
A View Model is used to adapt a model (as in MVC) so that it fits a view better. It's purpose is simply to remove logic from the view and hide details regarding the Model that should not be used/available in the View.
Neither a DTO or a ViewModel should be used for anything else unless you want to violate Single Responsibility Principle.
What you are asking for should be done in your Controller (since it's the glue between the Model and the View). Hence add the ICalculator to the constructor of your controller.

Splitting up a class into sub-classes

I've got a business logic layer class containing access methods for each table in a database. As there are quite a few tables now I'd like to restructure it to group the methods by entity (for easier access when coding). So, from this:
BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.UserGetById(42);
to this:
BLL.Database MyDB = new BLL.Database();
BLL.Entity.User MyUser = Database.User.GetById(42);
I'd like the class to remain non-static if possible, with all the classes 'partial' too (to allow me to add additional methods to the main generated class). What are my options for achieving this? Here's the current layout:
namespace BLL
{
public partial class Database
{
// private members..
// constructor
#region User
public IQueryable<BLL.Entity.User> UserGetAll()
{
// ...
}
public BLL.Entity.User UserGetById(int UserId)
{
// ...
}
public void UserSave(ref BLL.Entity.User user)
{
// ...
}
public void UserDelete(int userId)
{
// ...
}
#endregion
// More sets of methods for other entities in database here..
}
}
Is this feasible?
namespace BLL
{
public partial class Database
{
private _User;
public User
{
if (_User == null)
{
_User = new User();
}
return _User;
}
// Other data access classes here..
}
public partial class User
{
public IQueryable<BLL.Entity.User> GetAll()
{
// ...
}
// GetById, Save & Delete methods here..
}
}
Thanks.
Aside from the use of partial, your layout looks good. I don't think partial is going to do the trick for you as far as making the classes extensible, as partial classes must all reside in the same assembly.
A better solution would likely be creating extension methods.
Yes, that is feasible. In fact I implemented something a lot like that.
Of course, after doing so I heard about Linq to SQL and we started using that instead... so you might want to check that out as another option.

Categories