Workflow with MVC 4 - EF 5 - SimpleMembershipProvider - asp.net-mvc

So I want to build an application with MVC 4 and Entity Framework 5. I've build simple applications before, but now I need some security around my current effort... I have some confusion / questions that I was hoping someone could answer;
First... Using the MVC 4 Internet Application Template it implements SimpleMembershipProvider. I have read every primary article about modification, implementation... However, this uses a Code-First implementation...
Problem: I have an existing database that I would like to import the scheme for to an EDMX database first approach... How do I implement the MVC 4 Simple membership provider when my database ties tightly and directly into the user table (userid)?... I know I can use my own user table as long as i designate the userid and username fields as documented... Will this affect the provider, or the existing "AccountController" code? Will these need to be modified?
Second, what I am looking for is a workflow with this architecture... I am "old school" mostly database first approach... My project is a huge WIP (work in progress). I have a foundation, but will need to expand as needed... Can someone provide some insight into database first vs other approaches when there will be quite a bit of change management occurring?

you can still use Code First to map to an existing database. You may need to explicitly map properties to table columns because the mappings do not follow the default conventions, but that doesn't prevent you from using Code First.
When transitioning from DB first to another mindset. Focus on how the objects interact with each other. then, at some point you will save the state of the objects after they interacted. This is where the ORM comes into play. detects changes and executes the necessary SQL statements to persist the current state of the objects.
Think of the database as just another storage container. In theory it could be replaced by another persistent storage mechanism (document db, file, persistent hash table, in memory list, etc.). In reality it's not that simple, but the idea of treating the DB as just a simple storage container helps to break away from the monolithic database concept that is/was ingrained into most devs.
But don't loose perspective of the design either. If it's a simple forms-over-data app where you will be adding features in the future than keep the design simple. than don't try to totally abstract the DB away. you know it's there and the relationship to the UI is almost 1:1, so take advantage of that.
In it's simplest form separation of concerns can be achieved by using the MVC controller to manage the interaction between the model (mapped to the DB via ORM) and the view (razor templates) my personal preference is to keep ORM out of the views so I typically query the database, map the domain model to a viewmodel and then pass the viewmodel to the view.
Again if it's a simple application and screens map directly to the database than viewmodel are probably overkill.

Related

architecture of Umbraco application

I m new to Umbraco, I have watched Umbraco.tv videos and want to use Umbraco in a project as a cms for managing and editing content. I am highly thankful for your guidance, time and for your thoughts on 3 questions:
How a Umbraco based data driven proejct should be architecutured ? For custom database tables do you use a separate database or same Umbraco database ?
How you work with custom data (non content) ? Do you make everything a document type, even if it is data which you are not going to create content of, for example a simple form submitted data ?
For DAL what technology or ORM you use ? Does Umbraco provide any API for saving simple data which is not a content or document type ?
Thank you so much once again.
1 The architecture question is important but it also has be considered against how complex the project needs to be.
I would usually recommend a separate database for non-Umbraco data since this keeps everything nicely independent and manageable especially as projects grow. It also means that CMS-specific data (i.e. content) can be kept separately from none-CMS data, e.g. user registrations.
However, if the project is small and isn't likely to grow, keep it simple. Use the same database and piggy back off Umbraco's implementation of the Petapoco ORM. For example:
ApplicationContext.DatabaseContext.Database.Save(new Thing());
Or
var item = ApplicationContext.DatabaseContext.Database.Single(thingId);
2 For custom data, again it's a matter of need, maintainability and simplicity. Only use document types for what needs to be and can be stored in the CMS. My personal rule is that if it isn't content or organises content then it doesn't belong in the CMS. For example news and news categories obviously belong in the CMS. However, the comments made on an article have no reason to in the CMS.
3 With regards to DAL, as I have said, Umbraco has an implementation of Petapoco that can be used out of the box. If the project is basic enough, just use that. There is little point in using anything else unless you need some separation and/or some additional grunt in which case I would recommend using NHibernate or EF.
In addition to the points above,
Use NuGet;
Use the MVC mode of Umbraco, as it will provide you with substantially more flexibility. Check out the Hybrid Framework as it provides a very good start point for a robust and flexible project architecture;
http://www.youtube.com/watch?v=0PtzyrEFG7I.
You always need a doctype in Umbraco, even if a page doesn't offer any WYSIWYG type editability
I would recommend using a Service Oriented Architecture, and the .dlls you drop into Umbraco can call the service. You can then deploy this service and have full control over how you do data access. Choose whatever method you want. Most modern sites use an ORM and it doesn't matter which, although nHIbernate and Entity Framework are the favourites. Don't be frightened to mix and match a more direct form of data access though as it can give you more control, especially in situations where performance optimisation of large queries is important.
If you're not familiar with adding custom .NET functionality into Umbraco, Trying out adding .NET user controls into Umbraco will give you a good start, and to help you to understand how you can utilise your own .dlls in Umbraco:
http://umbraco.com/help-and-support/video-tutorials/introduction-to-umbraco/developer-introduction/using-net-user-controls.aspx
Anything custom I put in the same database as my Umbraco installation, but everything in custom tables. I don't touch the Umbraco tabes, I would not want to affect my future version updates.
Form submitted data I store in my own custom tables, I avoid creating content nodes with those, it's often tricky and doesn't give me the flexebility I often need. What I do instead is create an "Admin" document type, that is behind login (hard coded access, but easy to hook up to Umbraco users / members if wanted) and use my own custom UI to display my stored custom data.
I use PetaPoto (http://www.toptensoftware.com/petapoco/), it's a micro ORM that is added through a single file (installation is so easy then), using the same db connection string. Then I create custom models as I need and with with parts of the MVC. I normally stay away from route hijacking and rather use Surface Controllers and ajax calls for almost everything.
Hope this helps!
You can use the database containing the Umbraco tables for tables not used in Umbraco. If there are no hosting problems for you using multiple databases then you can simply link to a second database in the web.config - this would be safer than using the default Umbraco database as Umbraco packages often add database tables & there could be naming conflicts.
Viewing non-Umbraco data (eg from a database) is best done by adding macros that access the data using standard .Net patterns (eg razor scripts, .Net User Controls) & then in Umbraco you add in a reference to the macro in the template (view). You can use multiple templates (views) for any document type; so if you have a document type called 'forms' that contains no data you can use the 'allowed templates' checkboxes to say which view(s) are valid for this document type. When you add a content item you must specify a doc type at the start, but the template (view) can be changed at any time.
If you are storing data any .Net ORM will work with Umbraco (see http://en.wikipedia.org/wiki/List_of_object-relational_mapping_software#.NET) I've used Linq to Sql, Subsonic & Dapper before now - but there are lots of options.
Take a look at my example using umbraco within Onion Architecture
https://github.com/afroukh/OnionCMS

ASP.net MVC, I want one database, not multiple

I am following the guide on the asp.net site for learning asp.net mvc4.
Link : www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/
Thing is, I want to put my movies table in the Default connection. Because I want all of the data to be in ONE database and not two.
I mean. I am confused as to why I can't just have one database, with separate tables. Surely multiple databases will introduce latency, and also scalability issues to my project.
How can I get around this?
That Default connection points to your local db and is what is used for the forms authentication stuff. That db has all of the asp.net role provider schema stuff in it and since it's an "internet" project this is where all the login stuff goes. if you want to have your entities and models hook into that same database when you add your entity framework model point it at that db and your good to go.
After a little further investigation:
It looks like http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-model is where you define your connection string for your entities. I noticed AttachDbFilename=|DataDirectory|\Movies.mdf in there, and after verifying my thoughts http://social.msdn.microsoft.com/Forums/en-US/sqldataaccess/thread/f21c0728-935d-492a-baaf-ff2704e3683b/ it looks like that is what is spinning up a second database in the app's data directory called movies.mdf. If you want to keep your 1 default database, change the connection string information in your MovieDBContext string to that of the default connection and and it should create your new movie structure within that same database.

EF + SQL Server: Code First or Database First

I have a system written in ASP.Net 2.0 Web Form. The framework that talks to MySQL Server is really cool. It reads all controls inside the server form tag or panel and does CRUD operations on the target table.
When I create the CRUD page, I just need to create the table in database user{id,name,password,createdate} and I just need to use id to be the exact column name in the table. The controls can be input/select/option/chekbox/textarea or even FCK Editor or CK Editor on the page. The framework loops through all the controls inside the Panel and save/edit/delete. If I want to add some new fields, email and mobile, I just need to add two controls on the page and add two more columns in the table. That's it. I don't have to change anything in page.aspx.cs file, Entity Layer, Business Layer or Data Access Layer. It is VERY easy to implement and maintain.
We want to upgrade the system to use ASP.Net 4 MVC3 with Entity Framework CT5. We will rebuild the whole system from the scratch. I was hoping some experts here could give me some pointers. I found the following two options to rebuild the system.
1. Code First
Our new system will do the exactly the same operations as the above framework. It will loop through all Request.Forms data and map them with its associate table in the database and save/update/delete all the data. To do this, view will post the form data, controller will accept the values with the Entity classes and save them to the database via EF. I still need to create ViewModel class to display data on View. If there is any change like adding email and mobile fields to user page, I still need to change three places view, entity(domain class) and ViewModel. I don't have to change anything in database as EF will automatically run ALTER TABLE to add two new fields. I still cannot figure out how to minimize the needs of both entity and viewmodel classes.
2. Database First
I really do not prefer this way but I will if this solution provides more flexible operations. I will create the columns in database, the system will dynamically create the ViewModel(I am still figuring out how to do that) reading all columns in the table, and display data on the page. When the view post data it needs to dynamically create the entity class and save the changes to the database.
EDIT:
Reasons of upgrading the current system.
We want to use the power of new features in .Net 4, Linq, Entity Framework, unobtrusive javascript library, easifer to work with JSON data, Remote Validation(We can use RequireFieldValidator, RegExValidator in current system but they are limited, for eg: validation on input checkboxes and option), duck typing with var and interface.
Our new system will do the exactly the same operations as the above
framework. It will loop through all Request.Forms data and map them
with its associate table in the database and save/update/delete all
the data. To do this, view will post the form data, controller will
accept the values with the Entity classes and save them to the
database via EF.
Someone please slap me if I'm missing something here, but these statements seem contradictory to me. If you want a system that will automatically parse the Request.Forms data and map them directly to a database table, then why would you need to use Entity Framework (or any other kind of middleware) at all? The point of EF, or any ORM, is to create a meaningful collection of conceptual data objects that represent your system's nouns. You then operate on those nouns, affecting their properties or accessing their behaviors, and let the ORM figure out how to map them to the tables + columns.
To answer your question, it sounds like you want the easiest solution, meaning the one where you have to write the least amount of code. If that is a correct assumption, then you might want to go with Database first. You can have EF generate your entity classes, but like you said, you will still have to either manually create viewmodel classes or come up with some kind of AOP (using T4 maybe) to generate these for you. But anytime you give a tool the power to generate something for you, you lose control over it.
I prefer code first / conceptual model first, but I also like to have complete control over everything in the application (aside from infrastructure concerns which can be delegated to tools and frameworks like AutoMapper, EF, T4MVC, etc). Yes, it is more work, because I have to create the entity classes, the viewmodel classes, and the views, (and controllers, and action filters, and html helpers, and rrrvrything else). If your domain is one where you can just map text boxes straight to database tables & columns, then maybe this would be overkill for you.

Domain Driven Design vs Database Driven Design for an MVC Web application

I am expanding/converting a legacy Web Forms application into a totally new MVC application. The expansion is both in terms of technology as well as business use case. The legacy application is a well done Database Driven Design (DBDD). So for e.g. if you have different types of Employees like Operator, Supervisor, Store Keeper etc and you need to add a new type, you just go and add some rows in a couple of tables and voila, your UI automatically has everything to add/update the new type of Employee.
However the seperation of layers is not so good.
The new project has two primary goals
Extensibility (for currently and future pipeline requirements)
Performance
I intend to create the new project replacing the Database Driven Design (DBDD) with a Domain Driven Design (DDD) keeping the Extensibility requirement in mind. However moving from a Database Driven Design to Domain Driven Design seems to inversely impact the Performance requirement if I compare it to the performance of the legacy DBDD application. In the legacy application any call for data from the UI would directly interact with the Database and any data would be returned in form of a DataReader or (in some cases) a DataSet.
Now with a strict DDD in place any call for data will be routed through the Business layer and the Data Access layer. This would mean each call would initialize a Business Object and a Data Access Object. A single UI page could need different types of data and this being a Web application each page could be requested by multiple users. Also a MVC Web application being stateless, each request would need initializing the business objects and data access objects each and every time.
So it seems for an MVC stateless application the DBDD is preferrable to DDD for performance.
Or there a way in DDD to achieve both, Extensibility that DDD provides and performance that DBDD provides ?
Have you considered some form of Command Query Seperation where the updates are through the domain model yet reads come as DataReaders? Full blown DDD is not always appropriate.
"Now with a strict DDD in place any call for data will be routed through the Business layer and the Data Access layer."
I don't believe this is true, and it's certainly not practical. I believe this should read:
Now with strict DDD in place, any call for a transaction will be routed through the business layer and the data access layer.
There is nothing that says you can't call the data access layer directly in order to fetch whatever data you need to display on the screen. It is only when you need to amend data that you need to invoke your domain model that is designed based on its behavior. In my opinion this is a key distinction. If you route everything through your domain model you will have three problems:
Time - it'll take you MUCH longer to implement functionality, for no benefit.
Model Design - your domain model will be bent out of shape in order to meet the needs querying rather than behavior.
Performance - not because of an extra layer, but because you wont be able to get the aggregated data from your model as quickly as you can directly from a query. i.e. Consider the total value of all orders placed for a particular customer - its much faster to write a query for this than to fetch all order entities for the customer, iterate over and sum.
As Chriseyre2000 has mentioned, CQRS aims at solving these exact issues.
Using DDD should not have significant performance implications in your scenario. What you worried about seems more like a data access issue. You refer to it as
initialize a Business Object and a Data Access Object
Why is 'initializing' expensive? What data access mechanisms are you using?
DDD with long-lived objects stored in a relational database is usually implemented with ORM. If used properly, ORM will have very little, if any, impact on performance for most applications. And you can always switch back the most performance-sensitive parts of the app to raw SQL if there is a proven bottleneck.
For what's it worth, NHibernate only needs to be initialized once on application startup, after that it uses the same ADO.NET connection pool as your regular data readers. So it all boils down to a proper mapping, fetching strategy and avoiding classic data access mistakes like 'n+1 selects'.

ASP.NET MVC models when using external web services

I'm getting started on a new MVC project where there are some peculiar rules and a little bit of strangeness, and it has me puzzled. Specifically, I have access to a database containing all of my data, but it has to be handled entirely through an external web service. Don't ask me why, I don't understand the reasons. That's just how it is.
So the CRUD will be handled via this API. I'm planning on creating a service layer that will wrap up all the calls, but I'm having trouble wrapping my head around the model... To create my model-based domain objects (customers, orders, so on..) should I:
Create them all manually
Create a dummy database and point an ORM at it
Point an ORM at the existing database but ignore the ORM's persistence in lieu of the API.
I feel like I've got all the information I need to build this out, but I'm getting caught up with the API. Any pointers or advice would be greatly appreciated.
Depending on the scale of what you're doing option 3 is dangerous as you're assuming the database model is the same as that exposed by the external service. Options 1 and 2 aren't IMHO much different from each other - in either case you'll have to decide what your objects, properties and behaviours are going to be - it just boils down to whether you're more comfortable doing it in classes or database tables.
The key thing is to make sure that the external service calls are hidden behind some sort of wrapper. Personally I'd then put a repository on top of that to handle querying the external service wrapper and return domain objects.
In general, ORMs are not known for their ability to generate clean domain model classes. ORMs are known for creating data layers, which you don't appear to need in this case.
You could probably use a code generation tool like T4 to code generate a first pass at your domain model classes, based on either the web service or the database, if that would save you time. Otherwise, you probably would just manually create the domain objects. Even if you code generate a first pass at your domain objects, it's unlikely there is a clean 1-1 mapping to your domain objects from either the database or web service, so you will likely need to spend significant time manually editing your code generated domain classes anyway.

Resources