Grails - #Transactional annotation on generating simple Controller - grails

Grails newb here. I was using GGTS to generate a controller for a simple User model (string user, string passed)
On looking at the GGTS generated code, I noticed that there is #Transactional annotation on certain actions like delete(), save() and update().
My question is, why is #Transactional used in the controller and why is #Transactional not used in Services?
Newb in grails

In grails the correct way to do all DB related work and DB transactions is to do in service classes and not controllers. So by default controllers don't have privileges to do transaction and hence we use #Transactional annotation. While in services by default transaction is allowed.
If you use a service method which does some DB transaction then you need to make your controller action transactional by #Transactional annotation. While no need to mention it in service method.
Other way round if you donot make the controller transactional then you will need to mention it in service class.
Best practice will be not to use auto generated code as it will be less maintainable for a beginner. Official documentation will be your best help and while doing it when you will create controller you will not find any transactional annotation while when you will create service class you will see transactional annotation at the class level.
P.S. - 'Create' class is not equal to 'generate'.

Related

Common functionality across multiple ASP.NET MVC controllers

I'm working on ASP.NET MVC application & have a quick design question for you.
So I need to implement a common functionality for all my controllers (well, most of them).
I don't want to repeat the same logic in all the controllers.
What'd be the ideal approach in the best interest of MVC?
I found people saying create base controller and inherit it in your controllers. But when I visualize a controller, I can see it'd contain only action methods that return some content/views - Correct me if I'm wrong.
OneController
{
ActionMethod A1
{
//Code to return list of objects for the given integer value. So it calls database stored procedure.
}
}
...multiple such controllers are there.
I'd still like to have A1 exists in the OneController, just put its logic somewhere common place.
Also some people suggest to create just plain Helper class to place the common method.
Could you please suggest me what approach will be better (Or any other appropriate approach)? Thanks.
I agree with you that, most of the times, it only makes sense to inherit from base controllers when we're talking about Actions or methods that are really related. But of course, you can just use base controllers for everything. Your choice.
Other than that, you have 2 options. For classes that have little to no chance of being polymorphic (change behavior depending on the implementation), you are fine to create static classes and just use them inside your controllers. An example would be a class that does math calculations, these are not that polymorphic by nature.
For all the other cases, I'd strongly suggest that you use dependency injection. One of the reasons being that unit testing will become way easier. Here's a guide on how to do it for MVC 4 onwards using the built in engine: https://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-dependency-injection. If you don't want to use it and use Ninject or Simple Injector, you can implement your own ControllerActivator and use Ninject, for instance, to get an instance of your controller.
When using dependency injector, normally your controller would get the dependencies in the constructor, like this:
public class StoreController : Controller
{
private IStoreService service;
public StoreController(IStoreService service)
{
// service in an injected dependency
this.service = service;
}
}
For more information, Google ASP.NET dependency injection.

Where is the "magic" happening when a Controller instantiates the correct implementation of the Interface in Web API DI?

It seems to me that somewhere a rabbit is being pulled out of a hat when it comes to DI in Web API Controllers.
I grok that:
0) The Controller in a Web API project can be called with various classes to be instantiated, all of which implement the interface on which the Controller depends. e.g., with this Controller code:
private readonly IDepartmentRepository _deptsRepository;
public DepartmentsController(IDepartmentRepository deptsRepository)
{
if (deptsRepository == null)
{
throw new ArgumentNullException("deptsRepository is null");
}
_deptsRepository = deptsRepository;
}
..."deptsRepository" can be a class that implements IDepartmentRepository and retrieves test data, OR it can be a class that implements IDepartmentRepository and retrieves production data, OR (etc.)
1) Web API decides which Controller is called based on the URI the client calls, and that Web API decides which method in that Controller is called based on what type (GET, POST) etc. it is and what args, if any, are passed with it.
2) Castle Windsor intercepts this automatic control of Controllers with its own replacement routing engine.
What I don't grok is just where the developer injects the concrete class that implements the interface expected by the Controller. IOW, if I want to run the class that pulls from test data, where do I add code to specify that? I would think it would be somewhere in Global.asax.cs, something like (pseudocode):
// Use test data for now
DeptsControllerClass = TestDataClass;
//DeptsControllerClass = ProductionDataClass;
IOW, where does one specify, "This time, I want you to inject THIS concrete class which implements the required interface"?
As you wrote at point 1, Routing and IoC are two different things.
Once the routing engine figures out which controller has to be invoked, a "controller factory" will be invoked.
WebApi framework allows to plug your own factory as following:
GlobalConfiguration.Configuration.Services.Replace(
typeof(IHttpControllerActivator),
new WindsorCompositionRoot(this.container));
Read more on Mark Seemann post about webapi&windsor plumbing.
Which concrete will be used to satisfy a given interface dependency, that's up to the ioc you choose to use within your factory as above. Using Windsor you may/should link interfce&concrete in the Installers.
Let me try to recap the whole process
1) Set up the routing in order to link url vs controller
2) create the container and register all components using installers
3) replace default controller factory w/ a factory working w/ your favorite ioc container(Windsor, I presume :-) )
4) Enjoy the magic.
All those steps happend in the Application_start within the Global.asax

ActionFilterAttribute ninject injection - DbContext has been disposed

I have my project which uses the usual Repository pattern with Services and Unit of Work (all with Ninject injecting the dependencies from a NinjectModule), but I'm trying to access a service from an ActionFilterAttribute to inject some information (from DB) in the layout of the pages I show so I don't need to mess with all the actions on each controller.
The problem comes when I save to DB on one screen and move to the next and then come back to the previous (with a standard #Url.Action): The ActionFilterAttribute for the Index action is triggered but the call to the service and corresponding repository (within the attribute) throw an exception because the DbContext has been disposed.
Is there any problem with accessing a service and, consequently, the DbContext from an ActionFilterAttribute while injecting the service via Property Injection? I want to make a note that I use property injection for the service in the attribute because the constructor receives 2 parameters that are arbitrary depending on the signature of the Action methods, so my only option was to inject via property.
Let me know if you need some code and I'll update the question.
I found the solution to my problem in the following question:
Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?
Combining Mark Seeman's answer with striplingwarrior's comment was the solution to it.
Basically I splitted my ActionFilterAttribute into an Attribute that merely decorated my Actions and keeps the parameters I need for later, and also into an ActionFilter that checked the Action's custom attributes and if my attribute exists, then it injects the data I wanted from the DB into the ViewBag. Everything is later binded with the BindFilter extension from Ninject so it applies only to the methods it needs.

Access/check Spring Security hierarchical roles programmatically

In my Grails project I defined multiple hierarchical roles using the Spring Security plugin e.g. ROLE_USER > SOME_OTHER_ROLE. When securing controller methods using the #Secured annotation it works just fine. However, I also would like to check the role programmatically in my code for one use case. Using the following approach I always get a false even though the user inherits the role through hierarchical role definition:
request.isUserInRole('SOME_OTHER_ROLE')
Also the following calls never directly return the inherited roles:
SecurityContextHolder.context?.authentication?.authorities
springSecurityService.getPrincipal().getAuthorities()
Is there a way of checking if the user also has the inherited role?
This seems like a bug (or at least an omission) in SecurityContextHolderAwareRequestWrapper which adds a request wrapper to implement the isUserInRole method.
You can use the roleVoter bean's extractAuthorities method. Add a dependency injection for it (def roleVoter) and then call
def allRoles = roleVoter.extractAuthorities(
SecurityContextHolder.context.authentication)

ASP.NET MVC – Mock Membership for Controller Test

I’m not sure how to mock an ASP.NET Membership for my controller test.
Controller Code:
MembershipUser username = Membership.GetUser();
string UserID = username.UserName.ToString();
Does anyone know how to mock this for a controller test? I'm using RhinoMocks.
I've started working on something like this. Rather than doing a true mock, I created a FakeMembershipProvider that just implements the minimum of MembershipProvider that I need and provides a way to set the users and such. I'm doing the same for RoleProvider. Then I've set the App.config for my test project so it uses these as the providers.
So far, it seems to be working well.
I would watch the MVS StoreFront Serieshttp://www.asp.net/learn/mvc-videos/
For one on Mocking -
http://www.asp.net/learn/mvc-videos/video-365.aspx
And the Membership one
http://www.asp.net/learn/mvc-videos/video-372.aspx
One for Membership and the view of refactor with OpenID
http://www.asp.net/learn/mvc-videos/video-425.aspx
To mock the objects connectected with Membership static class, you should use its Abstract classes in that case, for mocking the GetUser() method, use MembershipProvider class, it is possible to mock, just pass it to your controller and it's done.
Good luck, if you'll have any problems, just let me now, I'll post up some code examples.

Resources