When was the default AccountController sample changed? - asp.net-mvc

I asked this question over on the asp.net forums, and nobody seems to know what i'm talking about. I'm not sure why that is, but I figured I'll ask here to see if there is anyone with some insight.
Back when MVC2 was released, it included a sample AccountController that wrapped the built-in Membership and FormsAuthentication classes with testable interfaces and services. I read a lot about this, and it was considered a good thing because the Membership and FormsAuthentication classes were not easily testable.
Recently, I generated a new sample project with my up to date (SP1, MVC3, Tools Update, etc..) environment and I find that the AccountController is now much simpler. Gone are the Interfaces and MembershipService and FormsAuthenticationServices. The sample now calls the Membership and FormsAuthentication classes directly.
I'm wondering if anyone knows when this happened and why? Are the testable interfaces no longer considered correct? Was there a technical reason to change this?
The best I can figure is that this happened as a part of the change to remove a possible vulnerability when passing return url's on the open url.
Any insight?

The new model resembles EF's code first approach where the AccountModel is a POCO class. Inside the new API there are no longer abstractions but direct calls to static methods such as FormsAuthentication.SetAuthCookie making this code difficult to unit test. Not something I would recommend basing your real world application code upon.
And, yes, they have fixed a vulnerability inside the LogOn method which was not verifying if the return url is a relative url before redirecting.
Personally I would recommend you using abstractions in order to weaken the coupling between your controller logic and its dependencies. This will make the code easier to unit test.
For me passing all those domain models to views without using view models are total anti-patterns and I have never bothered with them. I simply create an empty project and do the things my way. I mean in the default project they even use ViewBag for Christ sake!

The Account Controller was changed with the MVC3 tools update (When they also included the use of jQuery via Nuget)

Related

ASP.NET MVC Data Access Layer

I'm working on an ASP.NET MVC project. In my solution I have the following projects:
BlogApp.Web (ASP.NET MVC app),
BlogApp.Data (Class Library)
I'm wondering how to implement data access layer. I want to use EntityFramework Code First approach. I was thinking about Repository pattern, but is this really necessary? I have read that it is only the next layer on top of ORM, which isn't really needed. So instead of writing method like:
GetAllPosts(Tag t) {
db.Posts.Where(p => p.Tags.Contains(t)).Skip(x).Take(y).Select(p => p);
}
I create db context in controller and write the same query? I don't need to implement paging and write wrappers around my models.
What you may have heard about the Repository pattern is that it's falling out of favour in some camps - see for instance Jimmy Bogard's blog. This doesn't mean that queries should be written directly in controllers, unless your application is very, very simple.
As has been noted, your queries should be written in only one place which your controller can then use - this would either be in a Repository method or in a dedicated Query Object, both of which provide better abstraction and avoid duplication.
Regarding simplicitly - is your application intended to have multiple front-ends which will require a separate assembly for your data access layer? If not you might want to consider merging the two assemblies and just using namespaces to keep things organised.
Not sure whether this question belongs here.
Anyway, if you write data access logic in your controller, and the same logic is required in another controller, what would you do? Copy-Paste this into new controller? That's just not good. Anytime, you are copying and pasting you need to step back, there must be something wrong here (aka code smell).
Separating the logic into different layer will make your code more maintainable and testable. Trust me!

Concerns about ASP.NET SPA(Single Page Application)

Here is my knowing about ASP.NET SPA:
have to use Upshot to talk to the server;
have to use DbDataController to provide Web APIs;
have to use Entity Framework Code first...
so, many concerns come out:
have to provide metadata for the upshot to work, this will obviously expose the structure of your database;
can i use Entity Framework Database First instead of Code First? You may ask why. Because Code First don't provide you the ability to customize your database(index customization, stored procedure...etc.);
A problem i met: when i add a "TestUpshot.edmx" file(generated from database 'northwind') to the MySpaApp.Models folder(trying to test whether i can use the edmx classes in the MyDbDataController class, and generate proper metadata in the client side), and run the application, there is an exception:"System.ArgumentException: Could not find the conceptual model type for MySpaApp.Models.Categories."...
Need help here, thanks in advance.
Dean
I may be missing something, but there is no requirement to use any of the technologies you've listed.
An SPA is just a pattern. You can use whatever you need to achieve that. There may be benefits with choosing certain technologies, ie templates, tutorials, etc.
Doesn't really answer your question, but should lead you to experiment with what you've got.
SPA is actually a way to conceptualize your client application. SPA comes the closest to the fat client - data server concept from the current web approaches. Definitely this will be the ruling concept within a couple of years.
Your concerns can be addressed using JayData at http://jaydata.codeplex.com that provides advanced, high level data access for JavaScript against any kind of EntityFramework back-ends (db, model or code first). Check out this video that presents the whole cycle from importing your EDMX from SQL (this could eighter be model first definition as well) to inserting a new product item in the Products table from JavaScript.

How can I provide my own ICustomTypeDescriptor in ASP.NET MVC?

I'm working on a small library for for ASP.NET MVC 3 that should offer better reusability of model metadata and easy mapping from data entities from / to custom viewmodels. For this I need to be able to provide my own implementation of ICustomTypeDescriptor for three different areas of interest in ASP.NET MVC:
Scaffolding
Validation
Modelbinding
It seems like this could be done by setting System.Web.Mvc.ModelMetadataProviders.Current to my own CustomMetaDataProvider, but this is not nearly enough to cover all three points above.
The problem is that there are several classes in System.Web.Mvc which call directly into this System.Web.TypeDescriptorHelper which is not extensible because it looks like this:
internal static class TypeDescriptorHelper {
public static ICustomTypeDescriptor Get(Type type) {
return new AssociatedMetadataTypeTypeDescriptionProvider(type).GetTypeDescriptor(type);
}
}
The only solution I found is very awkward and required subclassing lots of types from System.Web.Mvc to make it work. I even had to re-implement CustomModelBinderDictionary completely only to overwrite one or two lines of code. So it works, but it is a very messy hack and likely to break the next time I update to a new ASP.NET MVC version.
So here's what I like to know : Did I miss any simple way to do this?
Bonus question: If not and you are from the MVC team, could you consider creating an appropriate extensibility point in MVC 4 ;-)?
Edit: In reply to the question why I need to code my own TypeDescriptor: There are several reasons for this:
1. Most important: I need a workaround for the problem described at https://forums.asp.net/t/1614439.aspx/1
2. Also, I need to insert metadata dynamically for various reasons. For example I want to code my own Bind attribute, but BindAttribute is sealed. So instead of deriving from it, I am emitting a matching BindAttribute dynamically from the TypeDescriptor when detecting my own bind attribute implementation.
According to Brad Wilson (an ASP.NET MVC team member) this issue has been put on the bug list for MVC 4. So it seems there is no good solution for the moment, but hopefully this will be solved when MVC 4 comes out.
For anyone interested in my library for reusable validation and scaffolding metadata and model / viewmodel mapping, feel free to subscribe my blog at https://devermind.wordpress.com/. I'm going to release the library there.
I'm not sure what it is that you're trying to do with custom implementations of Validation, ModelBinding and potentially ModelMetadata, that can't be done with the DependencyResolver functionality in MVC?
The new scaffolding support in the recent Tooling Update for MVC 3 may meet your needs for scaffolding; however I would take a look at possibly hooking into the DependencyResolver functionality for the ModelBinding, ModelMetadata and Validation and see if they can achieve what you are looking for. I had a similar situation recently where I needed to implement a lot of these behaviors from scratch to provide a flexible framework, and I was able to do so with just ModelMetadata and Validation providers using IoC. I also ended up inheriting DynamicObject (or ExpandoObject) in a few cases to give even more flexibility. I know this isn't exactly a direct answer but I'm not sure why you would need access to anything lower than these extensability points?
EDIT: If you're looking to reuse ModelMetadata on similar ViewModels to avoid having to redefine the same ModelMetadata over in multiple places, you might want to consider the implications of this. There are many times when you want certain data restrictions on your entities but these restrictions should be on the DataModel and not the ViewModel. The user may have a slightly more restrictive rules. For example, you may stipulate that certain fields are readonly for the user in the ViewModel, but that the entity used as a DataModel does allow you to modify the value (typically from within your code). Similarly you may run into situations where the ModelMetadata used to generate the Create view for the VideModel might be slightly different than the ViewModel used for the Edit view. Reusing them may seem like a great way to stay consistent and reduce code duplication but it may be something you regret later on. I recently ran into the same issue where I wanted to avoid writing a new ViewModel for each view that may cause a postback, I haven't found a perfect solution I like but I think reusing the ModelMetadata will cause more problems that it might solve in my opinion. Writing ViewModels for views that need them will also probably eliminate your need to implement a custom BindAttribute implementation and the Scaffolding issue.
If I'm right in assuming not wanting to create so many ViewModels with their own Metadata is what's causing you to try and find implementations of a custom BindAttribute, custom Scaffolding, custom ModelMetadata, custom Validation and custom ModelBinding... it may be worth looking at how much time it would actually take to just create the ViewModels.
If you find a better approach, feel free to let me know :-)

Architecting ASP.net MVC App to use repositories and services

I recently started reading about ASP.net MVC and after getting excited about the concept, i started to migrate all my webform project to MVC but i am having a hard time keeping my controller skinny even after following all the good advices out there (or maybe i just don't get it ... ).
The website i deal with has Articles, Videos, Quotes ... and each of these entities have categories, comments, images that can be associated with it. I am using Linq to sql for database operations and for each of these Entities, i have a Repository, and for each repository, i create a service to be used in the controller.
so i have -
ArticleRepository
ArticleCategoryRepository
ArticleCommentRepository
and the corresponding service
ArticleService
ArticleCategoryService ...
you see the picture.
The problem i have is that i have one controller for article,category and comment because i thought that having ArticleController handle all of that might make sense, but now i have to pass all of the services needed to the Controller constructor. So i would like to know what it is that i am doing wrong. Are my services not designed properly? should i create Bigger service to encapsulate smaller services and use them in my controller? or should i have an articleCategory Controller and an articleComment Controller?
A page viewed by the user is made of all of that, thee article to be viewed,the comments associated with it, a listing of the categories to witch it applies ... how can i efficiently break down the controller to keep it "skinny" and solve my headache?
Thank you!
I hope my question is not too long to be read ...
This is the side effect of following the Single Responsibility Pattern. If each class is designed for only one purpose, then you're going to end up with a lot of classes. This is a good thing. Don't be afraid of it. It will make your life a lot easier in the long run when it comes to swapping out components as well as debugging which components of your system aren't working.
Personally, I prefer putting more of my domain logic in the actual domain entities (e.g. article.AddComment(comment) instead of articleCommentService.AddComment(article, comment)), but your approach is perfectly fine as well.
I think you are headed in the right direction. The question is how to instantiate your services? I'm no MVC.NET guru, but have done plenty of service oriented Java projects and exactly the pattern you are discussing.
In Java land we would usually use Spring to inject singleton beans.
1) You can do the same thing in .NET, using dependency injection frameworks.
2) You can instantiate services as needed in the method, if they are lightweight enough.
3) You can create static service members in each controller as long as you write them to be threadsafe, to reduce object churn. This is the approach I use in many cases.
4) You can even create a simple, global service factory that all controllers access, which could simply be a class of singletons.
Do some Googling on .NET dependency injection as well.

TDD with ASP.NET MVC 1.0

Where can I find a good tutorial on TDD with ASP.NET MVC 1.0? I'd prefer a video tutorial but a text tutorial would be fine as well. I have a new project starting soon and I want to start off on the right foot.
The Storefront Videos from ASP.NET are a must watch series.
Any tutorial on TDD will be helpful for MVC. I've been doing TDD for sometime and found that it was a natural transition in MVC. There are a few peculiarities that I have found that need to be addressed.
You often need to mock up the HttpContext, which means that you need to assign a ControllerContext to the controller after it's created as that's the only way to inject the mock. The context will be used to provide the Session, Request, and Response objects in the controller (also mock them). New HttpContextBase, HttpSessionStateBase, ... classes make this much easier to do.
Because of (1), invest some time in putting together some helper classes in a separate class library that can be used by all of your test projects. These helper classes should contain methods that provide configurable (or multiple methods to provide specific configurations) of the mocked contexts. This will help keep your tests compact.
Use and assign a ValueProvider for testing methods that accept parameters if you aren't using ModelBinding (with corresponding parameters in the signature) for a controller action. This will allow you to use TryUpdateModel/UpdateModel without adding code to your controller to get data from the Request into those methods.
Use a mocking framework -- if that isn't obvious from above. It will be so much easier to write your tests if you mock out the dependencies. Writing your own mocks, IMO, is not worth it, though I know others don't share that opinion. I guess this isn't unique to MVC, but I thought I'd mention it.
Set up a separate set of tests that use reflection to test that appropriate attributes with appropriate properties are getting set on your methods. MVC makes heavy use of attributes for security and other cross-cutting aspects. These need to be tested as well.
Check out here. MVC store front is highly recommended.
I thought that Rob Conery's 'ASP.NET MVC Storefront Starter Kit' http://www.asp.net/learn/mvc-videos/#MVCStorefrontStarterKit were great for demonstrating TDD with ASP.NET MVC.

Resources