"inheriting" ASP.NET MVC sites from a common template app? (multi-tenancy) - asp.net-mvc

We're building about 10 ASP.NET MVC sites which have a common set of features (and corresponding URLs, Routes, Controllers, Actions, and Views). The sites will also all share a base set of domain objects (e.g. users, companies) and base attributes on those objects (e.g. name, address, etc.).
But each site will also be highly customized and extended from the base. For example, our site for large, public companies will have "Subsidiary" and "Stock Symbol" fields on the Company domain object, while our site for startups will have a "Venture Firm" and and "Funding" attributes. Look and feel will also vary considerably, although we're trying to keep HTML as consistent as possible (modulo extra form fields for extra domain object attributes, etc.). We'll also be overriding images sparingly, so we can, for example, re-use the same button graphics across sites.
Anyway, we're trying to figure out how best to factor and architect things so that we can reuse as much code and as many tests as possible without limiting our freedom to add per-app attributes and vary the UI between apps.
I'm familiar with how to handle limited-customization multi-tenancy like you find in StackOverflow/SuperUser/ServerFault (or MSDN/TechNet for that matter), where the UI is a little different and the data model is more-or-less identical. But when the models and UI are very different (but inherit from a common base), I'm less sure how to proceed.
I'm less worried about operational issues, since we'll probably be running each site in a separate appdomain and hosting them on separate databases. I'm more worried about reducing long-term code maintenance costs, increasing agility (e.g. easy to add new features to the base without breaking derived apps), and realizing short-term dev-/test-cost savings as we build our 2nd, 3rd, 4th, etc. site.
I'm looking both for high-level guidance and suggestions, but also concrete suggestions for how to make that guidance real using modern ASP.NET MVC practices.
I realize this is a very general question, but for starters I'm looking for both high-level guidance as well as concrete tips-n-tricks for how to apply that guidance with ASP.NET MVC, including things like:
recommendations where to split base/derived across Visual Studio projects
source control tips to avoid forking
database schema tips (FWIW, our databases are all small-- under 10K rows per table, so dev/test cost is more of an issue than DB perf)
tips about re-using Controllers/Views/etc. corresponding to the "base" model attributes, especially re-using UI for things like "new customer" forms which will have a mix of base and derived attributes.
Anyone have good advice for how to architect a multi-tenant app like this?

Here's what we do, and it works pretty well for about 8 sites currently.
Define a core MVC project for your Controllers, ViewModels, HttpApplication, routes, etc. This will compile into a DLL and compromise the bulk of your site.
Create a basic set of default views, scripts, images, etc. for your site. These will server as defaults for your individual sites.
Per client, create any custom controllers, routes, etc that you'll need in a project that compiles to another dll.
Also per client, recreate any views, scripts, images that you'll want to use.
To make the above steps work together you'll need to write a little glue. The first piece of glue is a custom view engine. You'll want to customize the standard view engine to first look for views in your client-specific folder, and then the default folder. This lets you easily override the default layout per client.
The second method of getting everything working is to have your core application load the routes, controllers, etc from your client specific assembly. To do this I use the Managed Extensibility Framework (MEF) to expose a single Register method. Calling this method on my client assembly code registers the routes and any other client-specific needs.
Here's a general view of what my site folder structure looks like, with SiteContent being checked for views first:
- AppContent
- AppContent/Static
- AppContent/Static/Images
- AppContent/Static/Scripts
- AppContent/Static/Styles
- AppContent/Views
- AppContent/Views/Shared
- SiteContent
- SiteContent/Static
- SiteContent/Static/Images
- SiteContent/Static/Scripts
- SiteContent/Static/Styles
- SiteContent/Views
- SiteContent/Views/Shared
- web.config
- Global.asax
I have helpers that I can use like SiteImage and AppImage for use in my views. Also, I make each of my client sites use certain specific names for their master pages, that I don't ever define in my AppContent defaults.
I realize this is a rough overview, but it is working well enough for us right now.

I'm involved in a similar type of "suite" of projects currently which is focused on allowing customers to apply for products online but have very similar requirements for what information to collect, where the only differences are around product specific pieces of information or slightly different legislative requirements.
One thing that we have tried to do is create pages (model, view and controller combinations) that are reusable in themselves, so any application can use the page to capture information but redirect to the next page which may be different depending on what type of product is being applied for. To achieve this we are using abstract base controllers in the form of the template method pattern that contain basically all the required controller logic (including action methods with their applied action filters) but then use abstract methods to do the specific stuff such as redirecting to the next page in the process. This means that the concrete implementation of the controller used by specific application page flows may contain only one method which returns a RedirectToActionResult corresponding to the next page in the flow.
There is also quite a bit of other stuff that handles going backwards and those kinds of navigational things, but with the help of action filters you can get it set up that you don't have to worry about it once you get it up and working.
There are also base model objects which contains common functionality, be it validation logic or state persistence logic.
The data captured during the application process is persisted in database as xml serialized model objects which can then be pulled out and de-serialised once the application is completed and spat out in whatever format to whatever system the backend operations staff use to process applications.
The implications of this is that we have a project structure that consists of a base dll that contains top level abstract classes, interfaces and utility classes as well as html helpers, action filters etc. Then we have mvc projects which contain the concrete implementations of the base controllers, models etc as well as the views and masterpages.
The hardest thing is sharing views and I don't think we have properly got this sorted yet. Although with MVC 2.0 containing Areas I think this will become less of an issue but I haven't had a good play with it yet. (see Scott Gu's post on 2.0: http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx)
One thing I have POCed that looks like it will work is using a base MVC project to contain common views and then extending the default view engine to search that project on the web server when looking for a view to render (which is quite easy to do). Areas though is a far nicer solution.
As for source control, we are using svn and I think you are reasonable in being concerned about branches. It is not something that we have had to deal with yet, but we are probably going to go with git as it seems to make the process of branching and merging much less painful.
Not sure whether this helps you much but I would definitely recommend keep in mind abstract controllers and models, and also look at how you can use html helpers and and partial views to group similar pieces of functionality.

Mike Hadlow goes into good detail on how to accomplish this:
http://mikehadlow.blogspot.com/2008/11/multi-tenancy-part-1-strategy.html

One way to do this is to use branching in a source control system.
The main branch is for the common functionality. You then have a branch for customization and can merge changes out to the customization or back to the main branch.

Related

Where should I add a List All Users function when using MVC?

I'm aware that in model-view-controller, the Model is the class part.
If I have a User class and instantiate an object, the object must refer to a single user from the database.
So I'll have the CRUD methods on the user, for that specific user.
But if I need a function to run a SELECT * FROM Users, should I create a function within the User class? Or a function in a helper file? Or in the controller? Where should it go, in order to respect the MVC pattern?
I mean, it makes no sense to instantiate a User object just to run a function to display the Users table.
I'm not sure if this will raise "primarily opinion based" flags. I just don't know where those functions should go. If you guys consider the question worth closing, it's ok. But tell me in the comments in which stack community I should ask this.
Back up a bit. Let's go foundational for a moment.
In the MVC pattern
The model is your state (in simple terms), meaning a representation of the data important to the business functionality you are working with
The view is a way of presenting the state to the user (NOTE user here could be another system, as you can use MVC patterns for service endpoints)
The controller ensures the model gets to the view and back out of the view
In a system designed with good separation of state, business functions are not present in the model, the view or the controller. You segregate business functionality into its own class library. Why? You never know when the application will require a mobile (native, not web) implementation or a desktop implementation or maybe even become part of a windows service.
As for getting at data, proper separation of concerns states the data access is separate not only from the model, view and controller, but also from the business functionality. This is why DALs are created.
Before going on, let's go to your questions.
should I create a function within the User class? This is an "active record" pattern, which is largely deprecated today, as it closely couples behavior and state. I am sure there are still some instances where it applies, but I would not use it.
Or a function in a helper file? Better option, as you can separate it out. But I am not fond of "everything in a single project" approach, personally.
Or in the controller? Never, despite Scott Gu's first MVC examples where he put LINQ to SQL (another groan?) in the controller.
Where should it go, in order to respect the MVC pattern?
Here is my suggestion:
Create a DAL project to access the data. One possible pattern that works nicely here is the repository pattern. If you utilize the same data type for your keys in all/most tables, you can create a generic repository and then derive individual versions for specific data. Okay, so this one is really old, but looking over it, it still has the high level concepts (https://gregorybeamer.wordpress.com/2010/08/10/generics-on-the-data-access-layer)
Create a core project for the business logic, if needed. I do this every time, as it allows me to test the ideas on the DAL through unit tests. Yes, I can test directly in the MVC project (and do), but I like a clean separation as you rarely find 0% business rules in a solution.
Have the core pull the data from the DAL project and the MVC project use the core project. Nice flow. Easy to unit test. etc.
If you want this in a single project, then separate out the bits into different folders so you can make individual projects, if needed, in the future.
For the love of all things good and holy, don't use the repository pattern. #GregoryABeamer has a great answer in all respects, except recommending you create repository instances to access your entities. Your ORM (most likely Entity Framework) covers this, and completely replaces the concepts of repositories and unit of work.
Simply, if you need something from your database, hit your ORM directly in your controller. If you prefer, you can still add a level of abstraction to hide the use of the ORM itself, such that you could more easily switch out the data access with another ORM, Web Api, etc. Just don't do a traditional unit of work with tens or hundreds of repository instances. If you're interested, you can read a series of posts I wrote about that on my blog. I use the term "repository" with my approach, but mostly just to contrast with the typical "generic" repository approach you find scattered all over the interwebs.
I'd use some kind of 'Repository' layer. Then, my controller calls the UserRepository GetAll method and sends the data to View layer.

How to simplify MVC pattern for a demo purpose?

I have to set up a Asp.net demo using MVC 4 in a web application in order to help decision for a product that currently don't use this pattern. The model, view and controller should be simple, I just have two or three entities and a few pages.
I suppose I don't have to implement the whole infrastructure with services, repositories, etc. So how could I simplify the MVC components without loosing those advantages?
The MVC components aren't related to the data access strategy which you can use. To put together a quick demo (or a simple application) you can leave the data access in the same project but eventually split that out etc.
You can use something like AutoMapper to map from your entities to your view models if you want to put that level of abstraction in. You can also use EntityFramework contexts in the controllers to avoid additional levels of abstraction and only put in a simple interface/abstraction into one controller to show unit test ability.
Small examples of different patterns which could be used in the application is probably the way to go for the demo/presentation and not worry too much about putting them in all over the place. Remember the presentation and the delivery of information is as important, it not more, than the demo code itself.

Is MVC Framework ill-equipped for rich page design?

Just to prefix this question, I've decided to take a look at moving our works old legacy systems (40+ programs from vb6, vba, vb.net to c#.net) into two separate systems using the same DAL (barcoding terminals and one web based system) as I spend most my day fixing crummy or non existant business logic in 15 year old vba programs. I've recently built an entity framework model complete with fluent validation and couldn't be happier with it after using it for a bit.
The small team is familiar with webforms (but not very) but the last few days I've explored MVC Razor. I was loving MVC Framework until I tried to start trying to add more functions onto the same page and then it seemed arbitrarily hard to replicate our a recent system I put in a webform. Before, I would eager load a customer and all it's child entities and then bind that to single page for the customer so they could access everything (which is what they wanted), it works okay and isn't slow. From this single page I could edit all their account details/contacts/emails/phones/jobs.
All the examples I've done and seen in MVC handle a single update, a single edit etc but surely you can't separate out every single action into a new view/page? I can pass a rich model through to the view in MVC, but then its a pain trying to update all the different child entities.
This is probably the exact design that MVC wasn't designed for maybe, which is okay, I'm willing to adapt it if MVC will be a better platform going forward, but how are you meant to handle adding this complexity in? Some methods I've seen:
Lots of partial views? passing child info to them (or the id and lazy loading it)?
I've seen methods that wrap multiple <forms> around everything and handle actions that way.
Separate pretty much every task out
If the solution is more lightweight and easier to maintain I'll go research whatever I need to I just wanted at an earlier stage to see if I'm wasting my time. Any pointers to the correct questions I should be asking would be greatly appreciated.
ASP.NET MVC is neither more or less better equipped to deal with complex pages than any other technology out there.
Certainly, MVC requires more low-level work than a Web Forms app, with no direct binding support, but in most cases this is a good thing and provides much more flexibility in how your page is rendered.
One of the whole ideas of MVC is to give you more control over things, but that control leads to requiring more knowledge and more effort on your part in most non-trivial cases. MVC provides a number of tooling functions to speed up trivial work (like creating standard table based CRUD) but when you have complex models, you will have to do much of the work yourself.
This is not that MVC is "ill suited" for it, but just that control and flexibility has a trade off with more responsibility on your part.
In your case, you simply create a view model with all the fields you want. Then, you create your form to edit those fields. In your controller, you will need to unflatten that view model and create or update the necessary records in the database. It's not difficult, but it's more work than WebForms databinding.
You could look into more advanced tools (commercial) for MVC, such as Telerik's tools, which have developed more of a databinding like interface, but MVC is not a drag-n-drop technology, and requires you to hook things up and write the various logic for what is done.
If you need drag-n-drop, databound functionality, then no.. MVC is not the correct technology. But then WebForms requires you to accept many compromises as well, and ties your hands in many ways.
You could use partial views, however I seldom use them. I prefer to instead use Editor/DisplayTemplates as these take care of naming your form fields correctly, even for collections and complex objects. PartialViews tend to have lots of gotchas if you aren't careful. I pretty much only use them as fancy includes, or when using Ajax.
I'm not sure what you meay by "wrap multiple <forms> around everything`. You cannot nest forms in HTML, it's not legal. If you mean place a form around each row of a table, that isn't valid html either in most cases (it's not legal to put a form in a between the table and the tr).
It would help if you had a specific problem that you could ask about, vague objections don't help us solve your issue.
You can accomplish anything in MVC that you can in WebForms. The difference is MVC will usually require you to write more code as it doesn't really offer you any "controls" to drop on your page.
In WebForms, it's easy to create a master/detail view with a GridView, FormView and then wrap everything in an UpdatePanel for automagical AJAX support.
In MVC, while you do have helpers like the WebGrid and AjaxHelpers extension methods, creating views and/or pages requires more understanding of how things work to get the desired functionality. When I start a new MVC project, here's what I include:
Backbone.js - client-side "ORM" that performs CRUD operations
against RESTful* APIs
Knockout.js - client-side view models and
real-time data-binding for your views
Knockback.js - wraps
Backbone models in Knockout view models
Using these three frameworks, you can quickly create powerful single-page apps using MVC and WebAPI.

Web framework with really good admin/CRUD module?

Lot's (if not most) of the current Web frameworks provide an admin module for basic CRUD operations, but I find the ones I know usually very limited...
So, my question is, which Web framework out there provide the best administration backend?
By the best, I mean namely:
Domain objects that can be heavily polymorphic. Attributes/relations defined in a class appear when editing a record/instance of any of it's subclasses (and sub-subclasses, and sub-sub-subclasses, etc).
Abstract classes. It's ok to have abstract classes anywhere in the domain classes' hierarchy. Their attributes and relations also show in the records/instances of all descending classes.
Relations. Allow to edit (out-of-the-box) the records/instances that have many-to-many relations, and relations with associative classes (e.g., django calls these intermediate models)
Extension. Allow to extend the admin so that we can use our own "UI controls" for specific domain objects. Some information is just too "exquisite" for an out-of-the-box form-based control to work in a suitable way.
UI Components. Instead of having to choose between using all of it or none of it, it'd be nice to have generic "UI controls" that one could reuse from within any page of the website, to edit specific domain objects.
Programming language is not an issue at this point, although I lean towards the languages (or frameworks) that allow me to express the most information at the domain model level (and that the admin module can then use to give me a richer UI).
I've been playing with Active Admin and Rails Admin for a couple of Rails 3.1 projects I am working on. While both are nice, I've migrated more and more to Rails Admin. I've found it easy to customize, it does a very nice job with associated models, and has a great default UI.
Rails Admin
Definitely good old WebObjects with it rule system called DirectToWeb. It generates everything at runtime based on rules. By default it can display all your entity's properties and relationships.
I guess that every current web framework will offer something like scaffolding, but often times, the work begins as soon as you change your model.
Check out this post and this teaser about the latest DirectToWeb-based framework, ERModern. You use nearly zero code for what you see in the video and you can build entire applications around it. It was sponsored by the iTunes team.
Edit for your bullet points:
Abstract classes and domain objects that can be heavily polymorphic - You handle these using rules.
Editing relations - No problem, it only depends on the design of your components. If you use ERModern, you get this for free.
Generic UI components - This is exactly how DirectToWeb works. You use (or define your own) generic components that display themselves according to the current entity (an object inheriting from EOEnterpriseObject) and the rules that fired for the current state (the D2WContext, essentially a big dictionary).
You can see all of this in action in the 45 minutes long ERModern Intro Video.
This isn't an easy question to answer.
You never specify what language you want to use, and you named some features, but how much of these features do you want.
I mean I could suggest a number of frameworks and tools for ASP.Net MVC or Web Forms but what if you're a PHP developer or a Java developer?
I could suggest SharePoint (and I generally dislike sharepoint, but everything you want is in SharePoint), but then the question to ask is.
How much flexibility and freedom do you want to customize or how much do you want the framework to do and you just be a code monkey.
So I will give you just my opinion.
I use ASP.Net MVC for my custom apps. It does all of what you want and allows me the most freedom to create and extend with tools if I so to do so. Plus out of the box there's a user databse with roles I can easily create out of the boss once I run the app for the first time.
Also CRUD is completely easy and straight forward out of the box. just check it out http://www.asp.net/mvc there's a tutorial section that goes through what you're wanting that you could complete in half a day.
Then there are some OR/M like NHibernate, Entity Framework, Subsonic use www.google.com to find tutorials for these if you're not familiar with them.
Then there's SharePoint it has a learning curve but once you get past it it's pretty straight forward as it's easy to pinpoint bugs, focus on the business logic and not worry aobut data base schema (as you don't even need to touch a database).
I love WebObjects.
WebObjects -> EntityModeler -> Wonder -> ERD2WModernLook -> ERAttachment --> ERRest
Bam. Done.

In MVC (Asp.Net MVC specifically), should a model be represented by a single view?

To me, this seems to make little sense, but after reading the information in the following:
http://weblogs.asp.net/scottgu/archive/2010/02/05/asp-net-mvc-2-release-candidate-2-now-available.aspx
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/#comment-35397( specifically some of the comments)
It appears that the idea behind Asp.Net MVC is that you have a one-to-one relationship between models and views. This seems to go against the DRY principle and several other standard programming practices.
For example, lets say you have a user account model and there are two views available to edit it - one for the user himself to edit it and one for the site admin to edit it. The admin has access to an additional field for something internal, required but the user cannot view/edit it. Per the model binding functionality and the beliefs described in the posts referenced above, I would need to create two separate user models, one for each page, and the only difference would be that additional field. This is just a simple example as well, I've got a few that I've seen where it would potentially mean 5 or 6 different models for the exact same object, just a few fields different between each view. That really doesn't make any sense to me.
I did not read the posts you mentioned, but there is nothing wrong with having one Model for a couple of views.
I would just have this one UserModel and use it in all Views, even if there are some fields that are not used.
If things get a bit more complicated but Users still have a lot in common you can either use aggregation for the usermodel (User.Address) or use Interfaces (User has fields street , and city and implements IAddress).
Both methods have their pros and cons - with aggregation used in the majority of situations.
EDIT
After reading the posts I saw that they deal with validation. This is a different story.
If you want to use DataAnotations you have to have different classes if validation varies. I dont use DataAnnotations - so I guess your class design might be different.
If you're using annotations, I'd strongly consider one "model" and multiple "viewmodels." We went with a viewmodel approach on our current app and have been reaping the benefits, because our basic model needs to be shown in a couple different views.
There is no official requirement to have only one view per model in ASP.NET MVC. In many cases that would lead to duplication of code.
I personally like to split model-view dependencies, that is, one view per model. It comes down to the fact that you never know how, say, a couple of very similar model-view pairs are going to evolve in the future. If they're separate, you just introduce changes in one and you don't have to "fix" the other views that were dependent on this model, or worse, to take extra work to create own models for them all at once.
TL;DR: Make many view models. They are cheap and flexible.
"This seems to go against the DRY principle and several other standard programming practices."
[Citation Needed]?
MVC doesn't change the fact that in any language or pattern you need to make a view model definition for each separate screen. Whether via attributes, via XML, via toggling web form controls, whatever.
The DRY principal usually pertains to repeating business logic. Repeating a FirstName property across a CRUD screen section really isn't a big deal. Even 5-6 times, whats that? 40 seconds?
If you mistake your view models for object oriented classes and not homoiconisticish screen representations you run the risk of filling them up will all sorts of inheritance and or business logic.
Your not really programming when you make dumb view definitions. This work could easily be done in an Access GUI or defined in XML. The fact that your screen-view-models are in C# just makes it easier to fill them up with data and ship them around and work with tools like WCF and Automapper.

Resources