asp.net mvc user permissions and views - asp.net-mvc

it seems there are 2 options when dealing with security permissions for views in mvc:
either handle the permissions control logic in the controller and direct the user to the appropriate view...
Or implement some form of security-aware HtmlHelper extensions that render (or not) appropriate form fields/data
am i missing any other options here? the first seems ridiculously un-DRY and the second seems to contradict the definition of a view...
so my question is: is there a better way?

I disagree with the idea that (2) contradicts the idea of a view. Rendering or not rendering a particular component of a view dependent on data received from the controller seems perfectly appropriate to me. Whether you choose to require the data to be in the model or if it can be used from other server resources depends, I think, on how pedantic you want to be. I choose rather to be pragmatic and simply use what is provided rather than fabricate a new model just to hold role-related information so in some circumstances (link my menu control) I simply do the role checking in the view logic.
It's important to remember that MVC is a pattern -- not a dictum. Where the pattern seems to work against you, it's okay to bend it a little. Likewise, DRY is a principle not a law. If it seems best to repeat a little code to accomplish a purpose better, go ahead and repeat it. Understand that you're creating maintenance issues for yourself, but don't let rigid adherence to a principle keep you from doing the "right thing."

Related

Keeping a controller thin (too many action methods)

I'm working on my first real ASP.NET MVC project and I've noticed that the controller I've been working in is getting rather large. This seemingly goes against the best practice of keeping your controllers thin.
I've done a good job keeping the business logic out of the controllers. I use a separate layer for that. Each action primarily calls a method in the business layer and coordinates the end result based on whether or not the modelstate is valid.
That said, the controller has a large number of action methods. Intuitively, I would like to break the controller down into sub-controllers but I don't see an easy way to do that. I could simply break the controller down into separate controllers but the I loose the hierarchy and it feels a bit dirty.
Is it necessary to refactor a controller with a large number of thin actions? If so, what is the best way to do this?
First, when you hear that it's good to keep controller code to a minimum, this mainly refers to keeping each action method as thin as possible (put logic instead into business classes, not into Views and ViewModels.) It seems you're doing this, which is great.
As for having "too many" action methods, this is a judgment call. It could actually be a sign of good organization, that you're having each action focus on one thing. Also, maybe you're using actions specifically for use with RenderAction? And, it could just be the nature of your solution that there are many things to do relating to your Controller's theme.
So, my guess is that you're probably fine. However, to make sure, on note paper break out the controller into 2 or 3 controllers, and sketch out how your stories would work moving from action to action. And if you find that your workflow works with more controllers, you should break it out. Especially if you're going to be adding to this functionality later. The sooner your break it out the better.
Good question.
I believe a "thin" controller may still need to be "wide" or "tall" depending on how you want to stretch the analogy. If there is no clean way to break up a controller that needs to do a lot of things, I don't think that's a problem as long as each Action is focused exclusively on preparing Views/ViewModels and is of limited code size.
Another structural option you have is introducing partial classes for logical groupings of actions. And using something like vscommands to group the files together.
I doubt anybody can come up with a magic number of actions that tells you when it's a good idea to break stuff up and introduce new controllers, it really depends on your domain.
Another solution can be to separate the controllers based on the business concepts of the actions that are included in them, but the route of each action is in accordance with the REST rules.
However, I think it is better to use this solution only in cases where there is a fat controller, otherwise, it is better to categorize actions based on their output resources.

AOP and Applying Security to UI Elements

I'm working on an application in which we are trying hard to keep Separation of Concerns as strongly as possible. We're finding that the cross-cutting concern of security creates a number of complications.
However, it looks like these can be mitigated using attributes and Aspect-Oriented Programming.
I understand it as far as applying aspects to domain layer code, but what if you want to apply it to UI elements? For instance, what if I don't want to display a button when a user does not have permission to execute that functionality?
In our MVC application, at this point we'd have to write (pseudo-code follows):
<% if (user.CanSeeSomeData) { <%=Html.TextBox("MyTextBox") } %>
But we'd like to control the display with attributes a la AOP if possible.
Any ideas?
Also, if there are 3rd party, open-source tools that would be useful, those suggestions are welcome.
I'd say that a view shouldn't contain much programming (or nothing at all). The idea of using AOP (or a la AOP) in a place where the P is forbidden doesn't look nice.
Let's design it in a different way. Usually views have some control keywords to do the basic stuff: conditions and loops. More intelligence and I'd say that you're mixing the controller role there.
So the if (user.CanSeeSomeData) you put there, if it is in fact a simple flag. It's the way views should be.
When you were building the modelview object (the container where you put the information for the view). You could have used AOP to initialize/set that information with a nice attribute in that property for example.
You could ask for attributes instead of "ifs"
[UserCanSeeData]
<%=Html.TextBox("MyTextBox") %>
This looks like syntactic sugar, not real AOP. Any attempt to say that UserCanSeeData should have more than an if (like a database access to check user priviledges), is an attempt to move controller code into the view.

Using Code-Behind with ASP.NET MVC Views

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.
Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.
I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.
Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).
Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.
I used code-behind extensively on my first ASP.NET MVC (Preview 3!) project - primarily for doing stuff like casting ViewData["foo"] into strongly-typed data objects, gathering view data into IEnumerables so I could loop across it, that kind of thing.
With the introduction of strongly-typed views, and pragmatic use of the (horrifically-named) Model-View-ViewModel pattern, I haven't missed code-behind at all since it was removed from the project framework just before the final release.
I now strongly feel that whatever processing you're doing in your view's code-behind, you are far better off modelling the result of that processing in your ViewModel, allowing the controller to perform the actual processing, and keep the view as simple and lightweight as you can. That'll let you test the processing logic, it makes the views easier to modify, and creates - I think - a much more elegant separation between transforming your data for display, and actually displaying it.
Yes the codebehind has long been the secret hiding place of business logic which as we all know should not be at the View level.
Code behind has been removed to stop naughty developers from being tempted.
I would recommend avoiding the codebehind in an MVC app at all costs. Using the code behind negates some of the values you get by using the MVC Framework such as separation of concerns, etc. You want to have your data access, business rules, type conversion and that sort of thing applied in the Model. If you find you need to convert your data types like Dylan mentioned, you may want to make ViewModels. The ViewModel would basically be the data from the actual Model you would like to display, in the format you wish to display it in.
Its probably best to avoid putting anything in the code behind when using MVC.
I would be interested to hear which part was being debated about, to go in the codebehind?
If you new to Asp.Net MVC, I really recommend spending some time going through the Nerd dinner example. There's a free EBook and source available here http://nerddinner.codeplex.com/.
Creating the simple demo from scratch is a great way to learn.
After doing this, it may shed some light on where the code you have in the codebehind, could alternatively go.
Note: If you do follow the EBook, grab the latest site.css file from codeplex, otherwise the virtual earth maps won't be aligned properly.
HTH
Ralph
It should be noted that "Code Behind" is a feature of the Web Forms view engine. It really has nothing to do with ASP.NET MVC itself.
For example, the Razor view engine in MVC3 does not even support it.
I would answer your question this way: If you cannot switch view engines without rewriting your controllers (or even your models) then you are not using the MVC pattern correctly.
Probably most of what you are doing in the .aspx.cs file should really be done before the model (or View Model) gets passed to the view. That said, in projects that I have migrated from ASP.NET Web Forms to ASP.NET MVC, I left a lot of the Code Behind in place. For example, I find it cleaner and more pleasing to use a Repeater control than to try to use a 'for' loop in Web Forms. I am still just iterating over View Model data after all. So why not? Separation of concerns is preserved (perhaps to a greater degree in fact).
I mean, why should "best practice" for Web Forms suddenly be the wrong way to do a Web Forms View? As a simple example, consider a Repeater that assigns a different CSS class to every second row of a table. Why should my controller (or even my model) care? Trying to put this kind of logic inline in Web Forms quickly devolves into tag soup and complete spaghetti. Now imagine something more complicated.
I have left Master pages in place that build the menus in the code behind. Again, all data comes from the View Model. I do not see why using GridView or other controls in this way should be a problem either.
I usually disabled ViewState in Web Forms anyway and did the data binding in "Init". Still, there would often be a small ViewState that I could not get rid of. I put some code in "Render" that moves this to after the form (it defaults to before). When moving to MVC, I sometimes left this code in. So, I have ASP.MVC sites that do indeed use Code Behind. I am just careful that it code that is specific to the view.
On new projects, I generally have found less of a need for Code Behind on most pages. Thankfully, view engines like Razor have made mixing code and mark-up in-line a lot less painful to write, read, and maintain.

ASP.NET web forms as ASP.NET MVC

I am sorry for possible misleading about the title, but I have no idea for a proper title.
Feel free to edit.
Anyway, I am using ASP.NET Web Forms, and maybe this isn't how web forms is intended to be used, but I like to construct and populate HTML elements manually. It gives me more control.
I don't use DataBinding and that kind of stuff. I use SqlConnection, SqlCommand and SqlDataReader, set SQL string etc. and read the data from the DataReader.
Old school if you like. :)
I do create WebControls so that I don't have to copy-paste every time I need some control, but mostly, I need WebControls to render as HTML so I can append that HTML into some other function that renders the final output with the control inside.
I know I can render a control with control.RenderControl(writer), but this can only be done in (pre)Render or RenderContents overrides.
For example.
I have a dal.cs file where is stored all static functions and voids that communicate with the database.
Functions mostly return string so that it can be appended into some other function to render the final result.
The reason I am doing like this is that I want to separate the coding from the HTML as much as I can so that I don't do <% while (dataReader.Read()) %> in HTML and display the data. I moved this into a CodeBehind.
I also use this functions to render in the HttpHandler for AJAX response.
That works perfectly, but when I want to add a control (ASP.NET Server control (.cs extension, not .ascx)) I don't know how to do that, so I see my self writing the same control as function that returns string or another function inside that control that returns string and replaces a job that would RenderContents do, so that I can call that function when I need control to be appended into a another string.
I know this may not be a very good practice.
As I see all the tutorials/videos about the ASP.NET MVC, I think it suite my needs as with the MVC you have to construct everything (or most of it) by your self, which I am already doing right now with web forms.
After this long intro, I want to ask how can I build my controls so I can use them as I mentioned (return string) or I have to forget about server controls and build the controls as functions and used them that way?
Is that even possible with ASP.NET Server Controls (.cs extension) or am I right when I said that I am not using it right.
To be clear, I am talking about how to properly use a web forms, but to avoid data binders because I want to construct everything by my self (render HTML in Code Behind).
Someone might think that I am appending strings like "some " + "string", which I am not. I am using StringBuilder for that so there's no slowness.
Every opinion is welcome.
You need to stop thinking in terms of "controls" and webforms. MVC is a completely different way of constructing applications.
I also hate the automatic renderers in WebForms, they produce horrible html that never makes any sense. However, you dont want to be writing your html in your codebehind and passing it around as strings, thats just nasty. Your presentation code is mixed in with your logic, AND youre writing HTML in c# strings!!!
So, MVC... Instead of "widgets" that do interacty things with codebehinds and postbacks, yours view ONLY display data and contain forms to allow you to post to the controllers.
Because of this, you can strongly type your views to a Type, and then access the data you pass to it from a controller via the Model property. The equivalent to UserControls are Partial Views (ViewUserControl) which can be used to modularise your rendering code for types. For example, you might make an Address partial to which you pass your Person's Address property every time you need it rendered. This way you aren't repeating html all over the place.
P.S. A single file for all your DAL?
I hope I never ever have to work on an app you wrote in this manner. If your application is string-heavy then something is wrong.
Agree with #sliderhouserules, the way you are using MVC framework is awful. You must forgot all your "old school" techniques.
You should never use SqlCommands, SqlReaders, etc. in the code of the pages. You should pass to the view only a model (e.g. View(bar)) and it will be better if you avoid usage of
ViewData["some magic string"] = bar
Every time when you will use "old school" technique 2 mans and 2 cats will be killed :).
Also it's better to use some ORM (Object-Relational Mapper) like Linq2sql, NHibernate, SubSonic, etc.
If you need in samples of good application design please look at SharpArchitecture. It has a very good architecture and implementation and may help a lot. It has one sample (with Northwind db) and one more sample will be added soon.
Also look at CodeCampServer. It has very good architecture too.
It's better to look at the code of these projects instead of looking videos because existing videos can't demonstrate good sample of architecture, just a simple usage of functionality.
About server controls, you may use them if they can be used without 'runat="server"', like PlaceHolder. And you may create them too, but you shouldn't load any data in them directly. If you don't want to copy-paste html you should review your code and you should refactor it. Every duplicated code should be moved to MasterPages of UserControls (ascx ones).
And once more, please spend some time to look at these samples. You'll save your nerves and time in the future when you'll need to update the app or fix something. At the first look they can be hard to understand but this is only at the first look.
Hope this helps.
#lopkiju, I think that the MVC pattern would serve you much better than your current WebForms solution if you want that much control over the output HTML.
You can use Web Forms this way as you already do, but it is not designed to be used this way, so it will be a pain.
More detail
In my opinion, read some articles about the Separation of Concerns (also known as SoC) principle. If you apply it correctly, it can save you many-many headaches when you'll debug your app, and also for those people who you work with (eg. those who may have to read or modify your source code).
My other tip for you is this:
You are right that you shouldn't do things like <% while (dataReader.Read()) %> in your View code. But perhaps there are better ways to make it more elegant than your current way.
I think you should consider using some sort of ORM for these purposes. (LINQ to SQL, or even NHibernate.) If you get it, it will be much simpler. So much that you may not want to use DataReaders directly again. :-)
What I recommend for you
Simply, read the NerdDinner tutorial, and build the samle app by yourself step-by-step.
After that, try to build a similar app that serves a different purpose by yourself while applying the same rules and design that you applied to the tutorial.
I'm pretty sure you have the expertise to do it, and after actually doing something with it, you can pretty much get the feel of it.
The tutorial also explains and includes the principles I mentioned above, which will be very much use to you.
If you want the ASP.NET MVC path, you can set up controls as ASCX and they will simply be tags filled by the controller. It may not be old school enough for you, however.
You can create your full UI in code behind, if you so desire. This can include creating the HTML in routines.
But, I would recommend, if you are sticking with ASP.NET, reconsidering the bind model over the DataReader.Read() and output + loop. It is not only old style, it is highly inefficient and hard to maintain.
ASP.NET MVC does create a much looser ASPX, as it is just a view. And there is a much greater separation of code and UI. But it will not fit with the old school model either.
Have you considered using micro-templates? Dave Ward has a good example of of a client side data repeater that is uses micro-templates for layout after making a call to a page method. This sounds like this is more in the spirit of what you are trying to accomplish and can still be integrated nicely with WebForms.
The side effect will be that you will not rely on passing around HTML and can isolate your presentation from your logic.

Code behind in ASP.NET MVC

What is the purpose of the code behind view file in ASP.NET MVC besides setting of the generic parameter of ViewPage ?
Here's my list of reasons why code-behind can be useful taken from my own post. I'm sure there are many more.
Databinding legacy ASP.NET controls - if an alternative is not available or a temporary solution is needed.
View logic that requires recursion to create some kind of nested or hierarchical HTML.
View logic that uses temporary variables. I refuse to define local variables in my tag soup! I'd want them as properties on the view class at the very least.
Logic that is specific only to one view or model and does not belong to an HtmlHelper. As a side note I don't think an HtmlHelper should know about any 'Model' classes. Its fine if it knows about the classes defined inside a model (such as IEnumerable, but I dont think for instance you should ever have an HtmlHelper that takes a ProductModel.
HtmlHelper methods end up becoming visible from ALL your views when you type Html+dot and i really want to minimize this list as much as possible.
What if I want to write code that uses HtmlGenericControl and other classes in that namespace to generate my HTML in an object oriented way (or I have existing code that does that that I want to port).
What if I'm planning on using a different view engine in future. I might want to keep some of the logic aside from the tag soup to make it easier to reuse later.
What if I want to be able to rename my Model classes and have it automatically refactor my view without having to go to the view.aspx and change the class name.
What if I'm coordinating with an HTML designer who I don't trust to not mess up the 'tag soup' and want to write anythin beyond very basic looping in the .aspx.cs file.
If you want to sort the data based upon the view's default sort option. I really dont think the controller should be sorting data for you if you have multiple sorting options accessible only from the view.
You actually want to debug the view logic in code that actuallky looks like .cs and not HTML.
You want to write code that may be factored out later and reused elsewhere - you're just not sure yet.
You want to prototype what may become a new HtmlHelper but you haven't yet decided whether its generic enough or not to warrant creating an HtmlHelper. (basically same as previous point)
You want to create a helper method to render a partial view, but need to create a model for it by plucking data out of the main page's view and creating a model for the partial control which is based on the current loop iteration.
You believe that programming complex logic IN A SINGLE FUNCTION is an out of date and unmaintainable practice.
You did it before RC1 and didn't run into any problems !!
Yes! Some views should not need codebehind at all.
Yes! It sucks to get a stupid .designer file created in addition to .cs file.
Yes! Its kind of annoying to get those little + signs next to each view.
BUT - It's really not that hard to NOT put data access logic in the code-behind.
They are most certainly NOT evil.
Ultimately, the question you ask yourself is this:
Does this code A) Process, store, retrieve, perform operations on or analyze the data, or B) Help to display the data?
If the answer is A, it belongs in your controller. If the answer is B, then it belongs in the view.
If B, it ultimately becomes a question of style. If you have some rather long conditional operations for trying to figure out if you display something to the user, then you might hide those conditional operations in the code behind in a Property. Otherwise, it seems like most people drop the code in-line to the front end using the <% %> and <%= %> tags.
Originally, I put all my display logic inside the <% %> tags. But recently I've taken to putting anything messy (such as a lengthy conditional) in my code behind to keep my XHML clean. The trick here is discipline - it's all too tempting to start writing business logic in the code behind, which is exactly what you should not be doing in MVC.
If you're trying to move from traditional ASP.NET to ASP.NET MVC, you might aviod the code behinds until you have a feel for the practices (though it still doesn't stop you from putting business logic inside the <% %>.
There isn't a purpose. Just don't use it except for setting the model
ViewPage<Model>
See this blogpost for more info.
At this Blogpost is a working example of removing the code behind.
The only problem I'm stuck with is that it is not able to set namespaces on the class.
The codebehind provides some of the strong typing as well as the intellisense support that you get in the view. If you don't care about any of these two features, you can remove it.
For example, I typically use the NVelocity ViewEngine because it's clean and pretty straight forward.
This is a great question. Doesn't MVC exist in the ASP.NET environment, without using the specific MVC pattern.
View = aspx
Controller = aspx.cs (codebehind)
Model = POCO (Plain Old C#/VB/.NET objects)
I'm wondering why the added functionality of MVC framework is helpful. I worked significantly with Java nd MVC and Java Struts several years ago (2001), and found the concepts in MVC to be a solution for the Internet Application organization and development problems at that time, but then found that the codebehind simplified the controller concept and was quicker to develop and communicate to others. I am sure others disagree with me, and I am open to other ideas. The biggest value I see to MVC is the front controller pattern for Internet development, single entry source for Internet Application. But, on the other hand, that pattern is fairly simple to implement with current ASP.NET technologies. I have heard others say that Unit Testing is the reasoning. I can understand that also, we used JUnit with our MVC framework in 2001; but I have not been convinced that it simplifies testing to use te MVC framework.
Thanks for reading!

Resources