Decoupling the view, presentation and ASP.NET Web Forms - c#

I have an ASP.NET Web Forms page which the presenter needs to populate with controls. This interaction is somewhat sensitive to the page-life cycle and I was wondering if there's a trick to it, that I don't know about.
I wanna be practical about the whole thing but not compromise testability.
Currently I have this:
public interface ISomeContract
{
void InstantiateIn(System.Web.UI.Control container);
}
This contract has a dependency on System.Web.UI.Control and I need that to be able to do things with the ASP.NET Web Forms programming model. But neither the view nor the presenter may have knowledge about ASP.NET server controls.
How do I get around this? How can I work with the ASP.NET Web Forms programming model in my concrete views without taking a System.Web.UI.Control dependency in my contract assemblies?
To clarify things a bit, this type of interface is all about UI composition (using MEF). It's known through-out the framework but it's really only called from within the concrete view. The concrete view is still the only thing that knows about ASP.NET Web Forms. However those public methods that say InstantiateIn(System.Web.UI.Control) exists in my contract assemblies and that implies a dependency on ASP.NET Web Forms.
I've been thinking about some double dispatch mechanism or even visitor pattern to try and work around this but I don't yet know in which direction I want to go and I would really like some input on the matter.

Not sure how a visitor would solve the problem. But why not have your contracts look like this:
public interface ISomeContract
{
void InstantiateIn(IControl container);
}
with an IControl implementation, possibly in another assembly to keep your contract assembly clean, that wraps over the ASP.NET System.Web.Control, like:
public class AspnetControl : IControl
{
public AspnetControl(System.Web.Control control) { }
// IControl members that dispatch to control
}
Although there's a high likelihood that eventually IControl would end up looking very much like a System.Web.Control (and hence defeat the point of abstracting it in the first place), it'd still be very testable, and your view and presenters won't have to know a thing about ASP.NET.

One way you can decouple your contract from your web control is to have a separate writer that handles getting the information from ISomeContract and places it in your Control container. This could reside in an assembly that references both the contract assembly and System.Web.

I have been reading about agile techniques, tdd, unit testing, solid, design patterns and felt utterly powerless to bridge the gap from all this wonderful theory to asp.net webforms.
I had another go at trying to find a solution to this problem earlier today and found this article:
http://p2p.wrox.com/content/articles/testing-aspnet-webforms
It is an excerpt from a book which I thought would solve all my problems but this chapter is really just an introduction to the possibilities of implementing the MVP pattern in webforms and it concludes with saying that its not really practical. The rest of the book is about testing asp.net MVC as far as I gathered.
There is also this new project which aims to bring the love back to the webforms platform:
http://webformsmvp.com/

In "normal" ASP.NET web forms, your page/user control is technically "in charge" of the processing, and imposes its life-cycle on the code. The page is the Presenter and the View, whether you like it or not.
Most attempts to implement the MVP pattern in this environment simply add excess complexity to an already overly complex environment! Pretending that another class is the Presenter is just that... pretending. (In MVC web sites, the Controller truly does control the code, and the View does not, so this argument no longer applies.)
My recommendation is to let the view look after its own life-cycle, and let it invoke Repositories and Model classes to retrieve/save data and invoke commands.
In this approach, the Model classes do not need to know anything about System.Web. These same Model classes could then be used in future MVC web sites, or Silverlight, or as a web service for WPF applications, or embedded in a WPF application, etc. It is up to the View to determine how to implement (using Controls) the response/data it gets from the Model.
The Model classes can be tested as much as you like if you correctly set them up to support dependency injection.
Hope that helps!

Related

How to use dummy class for external API at runtime (configurable)?

I need to fetch data from an external API, only accessible via VPN.
The development/test machine will not always be able to connect to the VPN.
The desired behaviour is to use two different implementations (one that calls the actual external API and one that acts as the real thing but returns dummy data). Which implementation to use will be configured via a flag in web.config
I've tried the IoC containers StructureMap and Unity and they both did the job but they only seem to be applicable for MVC, I'm looking for a generic solution that also works for web forms. And also, isn't it a bit overkill to use them for this isolated design problem!?
Is there a design pattern or best practice approach for this particular scenario?
IoC / dependency injection sounds like the correct approach, but you don't necessarily need a container for a simple scenario. The key is to have classes that depend on the API reference an interface IAPI, and pass it the actual implementation RealAPI or FakeAPI.
public class SomeClass
{
private readonly IAPI _api;
public SomeClass(IAPI api)
{
_api = api;
}
}
Now you should be able to switch out the implementation easily by passing a different object to MyClass. In theory, when you're using an IoC approach, you should only need to bind the interface to the implementation once, at the top level of the application.
isn't it a bit overkill to use them for this isolated design problem!?
They probably are. Those IoC containers only help you when you wrote loosly coupled code. If you didn't design your classes according to the SOLID principles for instance, those frameworks will probably only be in the way. On the other hand, which developer doesn't want to write loosly coupled code? In other words, IoC container solves a problem you might not have but it's a nice problem to have.
StructureMap and Unity [...] only seem to be applicable for MVC
Those ioc frameworks can be used in any type of application (as long as it is written in loosly coupled way). Some types of applications need a bit more work to plug a framework in, but it's always possible. StructureMap and Unity might only have integration packages for MVC, it's quite easy to use them in ASP.NET Web Forms as well.
Is there a design pattern or best practice approach for this
particular scenario?
What you're looking for is the Proxy pattern and perhaps the circuit breaker pattern.

Model-View-Presenter framework: In which project should the interfaces live?

I'm dabbling with the MVP design framework, and I currently have my solution set out as follows:
Project: MODEL
Contains: Concrete object class, DataRetrieval class, IDataRetrieval interface
Project: PRESENTER
Contains: Presenter class, IView interface
Project: VIEW
Contains: View class, Program class
I've been revisiting this solution when I can, but now I can't remember why I've got the interfaces distributed as they are. It doesn't seem right. I tried the following:
Move the interfaces into the relevant project for the classes that
implement them.
Move both interface to the presenter class.
Making either of these changes is going to require a little work, so I just wondered if either answer is better than the other (or perhaps both are very, very wrong :))
If it matters, this is designed in C#.
I'd love to hear your opinions!
Andy
Im just done with my custom MVP framework on Winforms. From my experience I can clearly identify the following sub-projects for any MVP implementation
Model Project
View Interfaces Project
Presenter Interfaces Project (It can sit along with the view interfaces as well)
Presenter Implementation Project
View Implementation Project (This is where your Winforms/WPF/ASP.NET stuff goes)
Application Controller (This is an important and often overlooked aspect of the MVP. It is responsible for starting the entire framework including the application itself. It also manages cross presenter communication and navigation)
Application Navigator (The navigator dishes out the concrete views and presenters when
demanded by the application controller)
I would like to suggest you add a separate project to your solution and call it YourSolutionName.Contracts. Move there all your View and Model interfaces, so your Presenter project won't have dependencies from these two assemblies (for more details check dependency inversion principle).

Application(solution) structure for Model View Presenter(+ Passive View) in WinForms?

Once upon a time I wrote a code that, with time, started to smell. It was not coded in a way that it could be easily tested. There were tight coupling on each of the children windows with database-centric Microsoft controls (like BindingNavigator, etc). But then it came the day when I was tired of my own code as it was not reusable, testable, or understandable (even by myself).
After reading about better ways to split presentation from business logic and database access/persistence, I came up with the first big change. I was then able to call a presenter for the children forms of my, let’s say, “MainForm”.
Nowadays, I have a bunch of Presenters, Views, Repositories, Models and Interfaces which I would like to organize in a “standard” project structure (i.e. projects like Business, Model, UI, Test). Can somebody expose such a structure, and, if possible, example folders they use inside each of them?
Also, should I use an only-one “MainPresenter”? or is it better to have one for each children form I will use, for example:
var searchReceivalPresenter = new SearchReceivalsPresenter(
new SearchReceivalsForm { MdiParent = this }, new SearchReceivalsRepository());
In my opinion I should keep several presenters.
Thanks in advance,
I think there may be some misunderstanding of MVP here - I wrote an article about how to do MVP with Windows Phone 7, but I cover the basics of MVP, and you should be able to understand the general theory and then apply it to WinForms:
Developing WP7 apps using the MVP pattern
But to quickly answer your question, every Form should implement a View interface, and every Presenter should handle 1 and only 1 View interface.
Where it gets tricky with WinForms is when you want to open a child Form. What I ended up doing is having the parent Presenter directly call a Show method on the child Presenter. The child Presenter would then use Dependency Injection to instantiate an implementation of the related View interface.
UPDATE (because I didn't fully answer the question) :)
Let me describe a project structure i've used for a winforms/MVP app:
/ - solution root
/[App]Core - project that contains the Model - pure business logic
/[App]Core/Model - data model (lowercase "m"), POCOs
/[App]Core/Daos - data access layer (all interfaces)
/[App]Core/Services - business logic classes (interfaces and implementations)
/[App]Ui - project that contains all UI-related code, but is UI-agnostic
/[App]Ui/Model - contains POCOs that are used by the UI but not the Core
/[App]Ui/Presenters - contains presenters
/[App]Ui/Views - contains view interfaces
/[App][Platform] - project that contains all UI-specific code (e.g. WinRT, WinPhone, WinForms, WPF, Silverlight, etc)
/[App][Platform]/Daos - implementation of DAO interfaces defined in [App]Core
/[App][Platform]/Services - implementation of business logic interfaces defined in [App]Core
/[App][Platform]/Views - implementation of view interfaces defined in [App]Ui
Is that more like what you were asking for?

C# MVC Pattern Help

I am having a go at refactoring my Winforms code into MVC pattern. I have never used this pattern before.
Obviously the GUI will be the view, the controller will be the 'middle tier' which is invoked by any user interaction with the GUI, and the model performs the requried tasks and informs the view of any status changes.
My question is, with the model, I am assuming that can span a great number of classes and is not confined to one 'model' class? Also, can these three sections all be within the same assembly?
Thanks.
for Winforms i wouldnt suggest MVC - id suggest MVVM
try this tutorial http://weblogs.asp.net/dwahlin/archive/2010/09/30/silverlight-sessions-coming-to-devconnections-las-vegas-november-1-4.aspx
this article mentions Silverlight but the MVVM pattern is generic and can be applied to Winforms
as pointed out by Roger Lipscombe - MVP may also work - try this for information on that http://davybrion.com/blog/2010/08/mvp-in-silverlightwpf-architectural-overview/ - again specific to Silverlight in this light but as its a pattern it can be adapted
For Winforms I would suggest learning about the MVP (Model/View/Presenter) and the MVC pattern. Although others have suggested MVVM might be a good idea I disagree - MVVM takes advantage of data binding offered in WPF and although Winforms supports binding to some extent, it's not as binding centric as the WPF architecture/object model.
The 'Model' layer can consist of many classes and I would always use the 'Single Responsibility Principle' as well as other Solid principles when modelling the classes within this layer of your architecture.
Useful links:
SRP - http://en.wikipedia.org/wiki/Single_responsibility_principle
SOLID - http://en.wikipedia.org/wiki/Solid_(object-oriented_design)
MVP - http://en.wikipedia.org/wiki/Model-view-presenter
No, model is not confined to one model class. In model you usually represent your database, and other data-related stuff. Controllers are responsible for most of the actions.
And yes, all this component will land in one dll. Bet there will be a lot of other files, like view files, which are not always compiled in MVC (but you can force that).
You might want to think about making a 'Model' class as an interface. Then all of your specific models implement that interface but share common methods (such as update, delete, etc.)
They can definitely be written in the same assembly. Your folder structure (strictly), should follow a Models/Views/Controllers structure, and place the code files underneath those respectively.
If you decide to try out the MVP pattern, which is a good choice for Winforms, check out MVC#, a framework for building MVP applications. It's simple and good.
Maybe you are interested in the approach I am heading for to combine the MVC/ MVP pattern with Databinding with fluent interfaces. mvc and databinding, what is the best approach?
If MVC, MVP or MVVM is used is from my point of view a matter of perspective. They will all lead to an abstraction of data, logic and visualization of the data.

Simple tips to reduce coupling

I have a large .NET web application. The system has projects for different intentions (e.g. CMS, Forum, eCommerce), and I have noticed a (naive) pattern of calling on another project's class. For example, the ecommerce module needs functionality to generate a file on the fly for products, and I call and reference a method in the CMS to do this, because file handling is really a job for the CMS.
Obviously (and I know why), this is bad design and a case of high coupling.
I know a few ways to handle high coupling, like restructuring the project (although I don't really think this is a robust solution), but what else can I do to reduce high coupling? Any simple tips? Also, it would be good to know why/how they reduce coupling. I use .NET 3.5 and Sql Server 2005 so things like JMS (which I keep coming across in my search for tips on this design issue), are not applicable.
Thanks
BTW,
One of the reasons I ask this is that I have read the previous questions similar to this but usually if a question that has been asked before is asked again, different tips can be learnt as different people reply to the post.
I know of dependency injection/IOC, but I am interested in the small things that can be done to reduce coupling.
How could I choose between using a static class, or an interface-derived class, or the IOC approach when deciding on how to reduce coupling? Also, I could develop a web service which could call a static class - mixing up the approaches in my solution.
The interesting thing is that in my application, I don't want it to be disjointed. So I just have a forum, ecommerce system, and any other module required, but everything has to gel into one site so each module (which is represented as a dedicated project in my Visual Studio solution) needs to know about every other module and work with it. So for example, I might have a module which handles user profiles (working with ASP.NET membership, roles, etc), but this will work with the forum module as a user on the forum will be a registered user on the site (one login throughout), and his or her profile will be coming from the user profile module. This is as opposed to seperate profiles as seen on other sites I've come across).
You should expose web services in those projects who will be needed by other projects. This is kind of the base level idea behind SOA. So, I would just create web services and consume them, which will decouple you quite a bit from how you have it now. Hope this helps.
I'd consider starting by doing an "extract interface" refactoring on the tightly coupled pieces. For example, if using the CMS as a backing store, create an interface that can store things, then create a mediator or adapter class that knows about the CMS, but isolate the logic that knows about the storage mechanism details to just that class.
Then, for testing, you can easily substitute an in-memory store or local-filesystem store that doesn't depend on the CMS being up.
Consider using techniques like dependency injection (See StructureMap, Spring.Net, NInject) to simplify instantiation if a simple factory doesn't give you the flexibility you need.
It sounds like you have a layering problem. Your assemblies should have a single dependency cycle - from least stable to most stable. That allows you to version sensibly. Generally, that cycle would be something like UI (least stable) -> Domain Core (stable) -> Data Access (most stable). You can throw in a Utilities or some infrastructre assemblies along the way, but again - they should be considered more stable than the assemblies dependent on them.
I'd guess your App.ECommerce and App.Cms assemblies are more siblings than layers - so you would not want those to depend on each other, but that doesn't mean you can't reuse functionality. For your particular scenario, you need to push the needed functionality down to a Core or Utilities assembly that both ECommerce and Cms can depend on. If it's a specific implementation that ECommerce provides, then you can push an interface or abstract base class to the Core - and have a higher layer (perhaps IoC container) wire up the concrete Cms.FileCreator class to the ECommerce.IFileCreator dependency.
Get proper abstractions in place as described by others (interfaces, etc). Program against abstractions, not concretions.
Design your classes with Dependency Injection in mind as you have described.
Use an Inversion of Control Container as the mortar between the bricks.
Unity from the Patterns & Practices team complements the Enterprise Library.
Scott Hanselman has a nice List of .NET Inversion of Control Containers.
Well, I don't know anything about .NET, but how about refactoring common code into a separate, underlaying project/layer? Loads of stuff in a web app can be done generically to suit both a CMS, a forum and eCommerce, writing to a file is a perfect example.
Another approach could be to see the forum and eCommerce as modules in a CMS, which would also make sense. Then they could safely use specified API:s of the CMS.

Categories