Facade pattern for asp.net mvc aplication - asp.net

I have an MVC2 application with the following classes:
-OrderModel
-LineOrderModel
-OrderController
-LineOrderController
In the OrderController class I'm recollecting some values of a web form . Until now, I created instances of each order line (LineOrderModel class) and OrderClass inside of the Controller.
I was trying to create a OrderFacade class in order to encapsulate the different things to do when creating an order.
So in that class I created a method like this:
public void saveOrder(int idProvider,decimal? price)
{
// Here I create instances of OrderModel and LineOrderModel
// and assign their properties
}
but my problem is I don't know how to pass all the order lines captured from the web form.
I think it doesn't make sense to create and pass to that method a List with orderLines class (because the point of this is to operate with the Facade, not with the class directly)
How could I encapsulate the different lines (all with properties like numberUnits,idProduct ...) into a List of generic objects, each one with these properties?
Maybe something like a List<List<object>> ?
Thanks in advance!

Sounds like you don't need facade. Facade would be good choice if you use data transfer objects (DTOs) between your business logic and application logic (controllers) - in such scenario DTOs can also be view models (I guess orthodox MVC developers will don't like this idea). Facade would take DTOs and convert them into some business or domain objects.
But in your scenario you simply need to fill data directly to your model classes - that is purpose of view model classes to use them in views and controllers. Using any kind of property bags to transfer data from controller to business logic is not a nice solution.

Related

ASP.NET Using one controller from another

I am creating an mvc project, for simplification i have two entitys: Movies and MoviesGenre.
I want to display a list of genres and the amount of movies each of them contains.
Now i have a problem with the design. I am not sure who is responsible for it. I solved that by creating a method in MovieController that returns the amount of movies by genre id and created a method on the MoviesGenreController that select all the genres and uses the MovieController(By instantiating an object) method to get their count.
That doesn't seems like good design to me. Which controller is responsible for this? Do I maybe need to create an extra controller for this logic? Thanks.
You need a data layer project which will manage the access of each controller to the underlying database.
I would suggest the following design:
create a library project (DataLayer) project which connects to the database.
Potential methods exposed:
List GetAllGenres();
List GetMoviesByGenre()
You can either inject the DataLayer as a service or just simply allocate a new object in each controller ctor. This is more like a personal preference... The DI approach is more flexible a more in line with the DotNetCore architecture.
Both MovieController and MovieGenreController should use the methods from the DataLayer.

ViewModel classes VS defining an Exclude Bind list on the domain class

I have a model class named Server, it contains many navigation properties and properties, which I want to prevent users from binding it. So I find two approaches of doing so to avoid over-posting attacks.
The first approach is to go to each model class and define an Exclude Bind list , with all the properties and navigating properties that should not be bind by users , as follow:-
[MetadataType(typeof(TMSServer_Validation))]
[Bind(Exclude = "Technology,IT360SiteID, VirtualMachines, TMSServer1,DataCenter,OperatingSystem,Rack,ServerModel,TechnologyBackUpStatu,TechnologyRole,TechnologyStatu ")]
public partial class Server {
}
}
The second approach is to create a view model class , with only the properties that can be modified by users as follow:-
public class ServerViewModel
{
public int ServerSize { get; set; }
[Required]
public String OperatingSystem { get; set; }
public String Commnet { get; set; }
}
I find that the first approach is faster to implement , as I only need to define the Exclude list, while the second approach will require me to create view-model class for each of the domain classes. So which approach is recommended to use and why ?
Thanks
Over-posting occurs due to the default model binder not knowing which fields you actually included in the form.
It will try to map all values in the request to object. Attackers can use your form to add additional fields to
query strings/form post data and add properties as part of the request. The default model binder won't
know the difference. Your Server class will deactivate once the mapping is complete and the update is processed.
To prevent over-posting, set the annotation to include fields in the binding, or create a ViewModel like you mentioned in your code.
So which approach is recommended to use and why ?
Both annotation and ViewModel allow binding only on specified fields, but when you use ViewModel you will not bind against business objects or entities, and you will only have properties available for the input you expected.
Once the model is validated, you can then move values from the input model to the object you used in the next layer.
k. Soctt Allen has a good article about which approach is better, you can take a look at by the following link:
http://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
It's difficult to tell without seeing the rest of your code, but in general I'd say using the ViewModel is probably a better approach for the following reasons:
You separate your view from your business logic
It is safer. If in the future someone adds a property on Server and forgets the Bind-exclude, you're exposed to over-binding without knowing it. If you use the ViewModel-approach you have to explicity add new properties
Maybe this question is a little bit ambiguous because the answers are going to be based on opinions or something. But I'll try to answer it the best I can and indeed is kind of my opinion. So this is the way I see it:
First approach (Bind attribute): Is faster to implement because you only need to add on your class the name of the property you don't want to expose, but the problems comes when you want your class to exclude some properties for one feature and other properties for another feature, and you can't add fields and sometimes in MVC, the views need more fields that the ones provided by the model class and then you're gonna need to use ViewBag or something else. This approach is very handy for fast and smalls projects, but I still don't like to use ViewBag (For aesthetics reasons)
Second approach (ViewModels): Is more work, and more time but at the end (again in my opinion) you get a cleaner and ordered code and you don't need to use the ViewBag, because you can have the perfect object to send to the view depending on what this View needs, so if you a have an object with different views, again depending on the needs, they could share the same ViewModel or they could have a ViewModel for each one. If you have a solution or a big web project, this approach is going to be very handy to keep an ordered code.
Let me know.

In MVP, how is Data Model complexity dealt with and where to dynamically show/hide controls?

In most of the MVP examples I've seen, the presenter calls some service, which calls some repository, which returns an entity. In most asp.net web applications that I have worked on, the logic is never that simple. In my last project, my presenter called a presenter service layer that had to jump through hoops to get the data that was to be shown on the screen.
Details: The service layer queries a database for, let's say, 8 entity objects, some of which are nested within each other, then the code maps those entities to one huge object base off of an XSD. That xsd object was then passed to a 3rd party library to do something with it. After it returned the processed xsd obj, the code then had to parse through that xsd object, using a middle layer view formatter class to extract and build what I call the "View Model" (I've heard some call it a DTO). This View model was then returned from the service layer to the presenter and then databound to a repeater.
Where does the logic for show/hide controls go? Should that be a member in the DTO or should the presenter derive this value? (I chose to have it as a member in the view model)
Is it ok to have nested ViewModels(DTOs) or should other user controls be used to break down the complexity?
What is a good way to wire up a presenter with all of the Pages/UserControls that use it; meaning one presenter with 5 IViews that require the same instance of the presenter. Should user controls be self contained or should they rely on the "parent" IView(page) to give it the proper presenter?
Instead of having a view model, why not just use the Interface that the Page implements and pass that to the service layer (through the presenter) and let the service hydrate the IView? (Doing this would cause the service layer to have a reference to it, isn't that bad?).
public class ViewModel
{
public bool ShowHeight { get; set; }
//Is there a bettter way to do this?
public List<NestedViewModel> NestedViewModel { get { return _nestedViewModel; } }
}
IMO, the view should manage itself in showing and hiding; it is the view and is responsible for managing the UI behaviour.
I think complexity is OK as long as its not too overbearing; you can break it down into nested subpresenters/views if you need to.
Most MVP frameworks populate the presenter/view relationship from the view, especially since ASP.NET runs in the context of the page (the page is the HTTP handler processing the request, so it's what is alive at that point). The page, during init, goes and establishes the view/presenter relationship. Most examples do it this way. I built an MVP framework and have also established this approach.
You could; that's considered passive view, though the presenter should still do the work, and not directly pass to the service layer.
This is my opinion and there are many ways to do this.

Fat ASP.NET MVC Controllers

I have been reading about "Fat Controllers" but most of the articles out there focus on pulling the service/repository layer logic out of the controller. However, I have run into a different situation and am wondering if anyone has any ideas for improvement.
I have a controller with too many actions and am wondering how I can break this down into many controllers with fewer actions. All these actions are responsible for inserting/updating/removing objects that all belong to the same aggregate. So I'm not quiet keen in having a seperate controller for each class that belongs to this aggregate...
To give you more details, this controller is used in a tabbed page. Each tab represents a portion of the data for editing and all the domain model objects used here belong to the same aggregate.
Any advice?
Cheers,
Mosh
For all your tabs you can use one action, that have an tab parameter, that indicate what data you need to return.
The controller job is to cast this string tab into enum type variable. Then the tab will be send to the repository, and the repository job is to return data in response to the tab value.
The controller should do its job through to services: Input Validator and Mapper.
The mapper service job is to map the user input (typically strings) into actual typed value (int, System.DateTime, enum types, etc).
The validator job is to check that the input is valid.
Following this principles should keep your controllers really tiny.
If you wanted something simple and easy I'd suggest just splitting up the controller into partial classes based on the tabs. Of course, it's still a fat controller there's just some obvious separation between the various tab functionalities.

ASP.NET MVC View information stored in a data-store

I'm looking for some advice on storing views in a data-store (database, file, other) and display them based on routing data, all using ASP.NET MVC 2 and ASP.NET Routing.
For example, I'd like to be able to display different views based on the following route data:
/{country}/
/{country}/{area}
But in the same vein I'd like to display:
/{planet}/
/{planet}/{satellite}
All are based on strings, and the data isn't fixed. So based on the number of segments maybe, use that as the selection criteria into the data-store...additionally, I may not know the segments up front, so they'd all be dynamic.
I'm was hoping we could get a few different methods together here, as kind of a reference for all - I'm sure some methods won't suite everyone...
So, how would you do it?
Branislav Abadjimarinov suggested a Controller Factory which could be used to do the look-up and display the page dynamically. I like this idea, what do you think?
There is no way for MVC to understand from this url's which route to choose. You have to make the routes more specific. For example:
/planet/{planet}/{satelite}
/country/{country}/{area}
You also have the option to define your own controller factory. The controller factory decides which controller to instantiate based on the route. So you can put some custom logic in it like - check if the {planet} parameter exist and if yes instantiate Planet controller else instantiate Countries controller.
This Post could be really helpful for you.
Remember you always can add a new routing rule : )
Just like this

Resources