How can I handle exception raised during Castle Windsor optional property injection? - exception

Castle Windsor 3.2 provides a cool addition that is Diagnostic logging in the container. This helped me redirect the container logs to a log4net log file that's being used to store the application logs.
What I'd like to do now is to be able to actually catch the Exception the container detects while injecting my optional property.
In my specific situation, an Oracle database error ORA-28000: the account is locked was being raised while Castle tried to execute my code to inject the Database property in a BaseController class:
public class BaseController : Controller
{
/// <summary>
/// Repository interface injected by Castle Windsor IoC container.
/// See <see cref="MyProject.Widgets.CastleWindsor.Facilities.PersistenceFacility.Init()"/> for more information.
/// </summary>
public ILogRepository Database { get; set; }
}
This Database property is null when I'm inside an action method in an Controller that inherits from BaseController. This all happens because Castle Windsor "swallows" the exception. The only message the user gets is: Object reference not set to an instance of an object. OK but I'd like to show the real exception/reason to the user, that is, ORA-28000: the account is locked. This message gets logged by Castle Windsor thanks to the aforementioned Diagnostic logging. This is cool but I want to be able to really catch the exception inside the catch block:
public class SubCatListController : BaseController
{
public ActionResult SubCatList(string subcat)
{
try
{
var sub = Database.GetLogSubCategory(subcat);
}
catch(Exception e) // I'd like to get the real exception from Castle Windsor here...
{
Logger.Error(e.Message, e);
}
}
}
Is this scenario possible with property injection?

As Krzysztof Kozmic mentioned in his comment we should not have any code that tries to do external object initialization while injecting a property.
My problem as I describe in this subsequent comment was that I was trying to open a database connection while initializing the property.
I removed that code and now the exception is only raised in my own domain code when that injected property is used for the 1st time.
Today I hit this same problem: one thing that helped me figure out the error was to momentarily use Constructor injection instead, like this:
private OEVizion _database;
public ReportingPeriodsController(OEVizion database)
{
_database = database;
}
Doing this I was able to see what was the error: version mismatch between log4net - the one in the OEVizion class library and the one used in the .Web project.
After getting the EF context correctly initialized I got back to Property injection and I'm back in business. :D

When you have optional dependencies it is always better to use the Null Object pattern.
public BaseController() {
Database = NullLogRepository.Instance;
}
It prevent the NullReferenceException and you can provide behavior you expect (do nothing, throw specific exception, log to trace etc.)

Related

How to use values from porperty files in a global context with Junit5 and CitrusExtension

Maybe I'm on the wrong course or totally misunderstanding something.
I've merged a Citrus IntegrationTest from Junit4Runner to Junit5 (with CitrusExtension).
There is an EndpointConfiguration class
#Configuration
#PropertySource("test-setup.properties")
#PropertySource("service-paths.properties")
public class RestEndpointConfig {
#Value("${testenv.host}") //defined in test-setup.properties
private String host;
...
}
And a TestClass
#ExtendWith(CitrusExtension.class)
#RunWith(JUnitPlatform.class)
public class BaseIT{
#CitrusEndpoint
protected HttpClient httpClient;
#Value("${rest.session}") //defined in service-paths.properties
private String sessionPath;
}
In the test class I want to access values defined in the service-paths.properties file.
This worked with JUnit4 but after the changes to JUnit5 it seems that the properties are no longer available in a 'global' context.
Turning the log level to 'debug' shows, that the properties file is loaded.
So my question is: What do I need to change in order to get access to the service-paths properies in my IT classes. What am I missing, what is best practice in this case?
Thanks in advance for any feedback.
Property value resolving via #Value annotation is a core Spring framework feature. So you need to add SpringExtension to your JUnit5 test. You can do this in addition to using the CitrusExtension.

How to hook interceptor for ILogger

I'm using the LoggingFacility, and need to add interceptor for the ILogger instances, created by the facility.
So far I tried to modify the component model for ILogger, and this didn't work, as the loggers are not really resolved using the standard resolving mechanism (they are created by a factory, which use some wrappers).
I was thinking to override the logging subresolver, but kernel.Resolver does not allow replacing (or wrapping) the resolver added by the facility.
I was thinking about hooking to Kernel.DependencyResolving, but it appears I can not replace the dependency there.
What is the most appropriate place to put such a hook, so I can add Interceptor for the ILogger.
EDIT: After a lot of poking around, I came with somewhat "hackish" solution, which unfortunately depends on small reflection usage.
The real problem appears to be, that the way the loggers are constructed does not follow (for me) the castle spirit of doing things. I.e. the resolver does not use the already registered logger factory, so it's impossible to add interceptors to the factory itself.
There is a great article about that on CodeProject: Aspect Oriented Programming (AOP) in C# using Castle DynamicProxy from Linjith Kunnon. It shows you how to define a Interceptor
public class LoggingInterceptor : IInterceptor
{
public void Intercept(IInvocation invocation)
{
var methodName = invocation.Method.Name;
try
{
Console.WriteLine(string.Format("Entered Method:{0}, Arguments: {1}", methodName, string.Join(",", invocation.Arguments)));
invocation.Proceed();
Console.WriteLine(string.Format("Sucessfully executed method:{0}", methodName));
}
catch (Exception e)
{
Console.WriteLine(string.Format("Method:{0}, Exception:{1}", methodName, e.Message));
throw;
}
finally
{
Console.WriteLine(string.Format("Exiting Method:{0}", methodName));
}
}
}
And how to register it with Castle.Windsor
kernel.Register(
Component.For<LoggingInterceptor>()
.ImplementedBy<LoggingInterceptor>()
);
kernel.Register(
Component.For<IRocket>()
.ImplementedBy<Rocket>()
.Interceptors(InterceptorReference.ForType<LoggingInterceptor>()).Anywhere
);
Please note that there is more valuable content in the linked article and that the whole code provided here is from the article and not from me. All kudos goes to Linjith Kunnon.
You need to create your own logger factory (derived from default implementation matching your logging framework) and then you can setup facility to use this factory like this:
container.AddFacility<LoggingFacility>(f => f.UseLog4Net().LogUsing<MyFactory>());
See full example here

Not able to fetch data from array in JSF [duplicate]

I've a data table as below:
<h:dataTable value="#{bean.items}" var="item">
I'd like to populate it with a collection from the database obtained from a service method so that it is immediately presented when the page is opened during an initial (GET) request. When should I call the service method? And why?
Call it before page is loaded. But how?
Call it during page load. How?
Call it in the getter method. But it is called multiple times.
Something else?
Do it in bean's #PostConstruct method.
#ManagedBean
#RequestScoped
public class Bean {
private List<Item> items;
#EJB
private ItemService itemService;
#PostConstruct
public void init() {
items = itemService.list();
}
public List<Item> getItems() {
return items;
}
}
And let the value reference the property (not method!).
<h:dataTable value="#{bean.items}" var="item">
In the #PostConstruct you have the advantage that it's executed after construction and dependency injection. So in case that you're using an EJB to do the DB interaction task, a #PostConstruct would definitely be the right place as injected dependencies would not be available inside a normal constructor yet. Moreover, when using a bean management framework which uses proxies, such as CDI #Named, the constructor may or may not be called the way you expect. It may be called multiple times during inspecting the class, generating the proxy, and/or creating the proxy.
At least do not perform the DB interaction job in the getter, unless it's lazy loading and you really can't do anything else. Namely, it would be invoked during every iteration round. Calling the service method during every iteration round is plain inefficient and may end up in "weird" side effects during presentation and postbacks, such as old values from DB seemingly still sticking around in the model instead of new submitted values.
If you rely on GET request parameters, then use <f:viewParam> and <f:viewAction> instead. See also Creating master-detail pages for entities, how to link them and which bean scope to choose.
If you want to preserve the model (the items property) across postbacks on the same view (e.g. CRUD table/dialog), then make the bean #ViewScoped, else the model won't be in sync with the view when the same model is concurrently edited elsewhere. See also Creating master-detail table and dialog, how to reuse same dialog for create and edit.
If you utilize JPA's #Version feature on the model, then you can catch OptimisticLockException to deal with it and show a message like "The data has been edited by someone else, please refresh/review if the desired changes are as intended". See also Letting the presentation layer (JSF) handle business exceptions from service layer (EJB).
See also:
Why JSF calls getters multiple times
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
How to choose the right bean scope?
JSF Controller, Service and DAO

primefaces datatable query twice [duplicate]

I've a data table as below:
<h:dataTable value="#{bean.items}" var="item">
I'd like to populate it with a collection from the database obtained from a service method so that it is immediately presented when the page is opened during an initial (GET) request. When should I call the service method? And why?
Call it before page is loaded. But how?
Call it during page load. How?
Call it in the getter method. But it is called multiple times.
Something else?
Do it in bean's #PostConstruct method.
#ManagedBean
#RequestScoped
public class Bean {
private List<Item> items;
#EJB
private ItemService itemService;
#PostConstruct
public void init() {
items = itemService.list();
}
public List<Item> getItems() {
return items;
}
}
And let the value reference the property (not method!).
<h:dataTable value="#{bean.items}" var="item">
In the #PostConstruct you have the advantage that it's executed after construction and dependency injection. So in case that you're using an EJB to do the DB interaction task, a #PostConstruct would definitely be the right place as injected dependencies would not be available inside a normal constructor yet. Moreover, when using a bean management framework which uses proxies, such as CDI #Named, the constructor may or may not be called the way you expect. It may be called multiple times during inspecting the class, generating the proxy, and/or creating the proxy.
At least do not perform the DB interaction job in the getter, unless it's lazy loading and you really can't do anything else. Namely, it would be invoked during every iteration round. Calling the service method during every iteration round is plain inefficient and may end up in "weird" side effects during presentation and postbacks, such as old values from DB seemingly still sticking around in the model instead of new submitted values.
If you rely on GET request parameters, then use <f:viewParam> and <f:viewAction> instead. See also Creating master-detail pages for entities, how to link them and which bean scope to choose.
If you want to preserve the model (the items property) across postbacks on the same view (e.g. CRUD table/dialog), then make the bean #ViewScoped, else the model won't be in sync with the view when the same model is concurrently edited elsewhere. See also Creating master-detail table and dialog, how to reuse same dialog for create and edit.
If you utilize JPA's #Version feature on the model, then you can catch OptimisticLockException to deal with it and show a message like "The data has been edited by someone else, please refresh/review if the desired changes are as intended". See also Letting the presentation layer (JSF) handle business exceptions from service layer (EJB).
See also:
Why JSF calls getters multiple times
What can <f:metadata>, <f:viewParam> and <f:viewAction> be used for?
How to choose the right bean scope?
JSF Controller, Service and DAO

entity and repository pattern with ninject, Dispose Issue

I have build my site using entity and repository pattern with ninject injection. My problem is my connections don't seem to get disposed. I have around 30 repositories (one for each table) and I get sql expiration timout preety quick. I can't use the regular using statement because the code recognize only the interface before the injection.
(in each controler I have my repositories interface instances which get injected via ninject).
I have searched the net but couldn't find a solution that was accurate for me.
can anyone please help me?
code example:
this is in the ninject controller under addBindings():
ninjectKernel.Bind<IMovieRepository>().To<MovieRepository>().InRequestScope();
and one of my repositories:
public class MovieRepository : IMovieRepository, IDisposable
{
private Entities dataContext = new Entities();
public System.Data.Entity.DbContext DbContext
{
get { return dataContext ?? (dataContext = new Entities()); }
}
public void Dispose() { dataContext.Dispose(); }
}
and in the Global.asax file:
ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory() as IControllerFactory);
I would guess that your repositories (and therefore presumably your DbContexts) are being bound in transient scope, which I believe means a new one will be created every time Ninject needs to inject one somewhere. I'm not certain but I'm guessing then that these are all staying around for the lifetime of your application and maybe not being disposed.
Try binding your repositories in request scope, so that they are created and disposed per web request.
e.g.
Bind<IFooRepository>().To<ConcreteFooRepository>().InRequestScope();
From the Ninject wiki:
There are four built-in scopes available in Ninject:
Transient - A new instance of the type will be created each time one is requested. (This is the default scope). Binding method is .InTransientScope()
Singleton - Only a single instance of the type will be created, and the same instance will be returned for each subsequent request. Binding method is .InSingletonScope()
Thread - One instance of the type will be created per thread. Binding method is .InThreadScope()
Request - One instance of the type will be created per web request, and will be destroyed when the request ends. Binding method is .InRequestScope()
This kind of problem usually occur if long living objects depend on shorter living objects. E.g. A singleton service uses a repository in request scope.