Why the getters in JSF2 Bean class are getting invoked even before submitting the Form elements? [duplicate] - forms

Let's say I specify an outputText component like this:
<h:outputText value="#{ManagedBean.someProperty}"/>
If I print a log message when the getter for someProperty is called and load the page, it is trivial to notice that the getter is being called more than once per request (twice or three times is what happened in my case):
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
DEBUG 2010-01-18 23:31:40,104 (ManagedBean.java:13) - Getting some property
If the value of someProperty is expensive to calculate, this can potentially be a problem.
I googled a bit and figured this is a known issue. One workaround was to include a check and see if it had already been calculated:
private String someProperty;
public String getSomeProperty() {
if (this.someProperty == null) {
this.someProperty = this.calculatePropertyValue();
}
return this.someProperty;
}
The main problem with this is that you get loads of boilerplate code, not to mention private variables that you might not need.
What are the alternatives to this approach? Is there a way to achieve this without so much unnecessary code? Is there a way to stop JSF from behaving in this way?
Thanks for your input!

This is caused by the nature of deferred expressions #{} (note that "legacy" standard expressions ${} behave exactly the same when Facelets is used instead of JSP). The deferred expression is not immediately evaluated, but created as a ValueExpression object and the getter method behind the expression is executed everytime when the code calls ValueExpression#getValue().
This will normally be invoked one or two times per JSF request-response cycle, depending on whether the component is an input or output component (learn it here). However, this count can get up (much) higher when used in iterating JSF components (such as <h:dataTable> and <ui:repeat>), or here and there in a boolean expression like the rendered attribute. JSF (specifically, EL) won't cache the evaluated result of the EL expression at all as it may return different values on each call (for example, when it's dependent on the currently iterated datatable row).
Evaluating an EL expression and invoking a getter method is a very cheap operation, so you should generally not worry about this at all. However, the story changes when you're performing expensive DB/business logic in the getter method for some reason. This would be re-executed everytime!
Getter methods in JSF backing beans should be designed that way that they solely return the already-prepared property and nothing more, exactly as per the Javabeans specification. They should not do any expensive DB/business logic at all. For that the bean's #PostConstruct and/or (action)listener methods should be used. They are executed only once at some point of request-based JSF lifecycle and that's exactly what you want.
Here is a summary of all different right ways to preset/load a property.
public class Bean {
private SomeObject someProperty;
#PostConstruct
public void init() {
// In #PostConstruct (will be invoked immediately after construction and dependency/property injection).
someProperty = loadSomeProperty();
}
public void onload() {
// Or in GET action method (e.g. <f:viewAction action>).
someProperty = loadSomeProperty();
}
public void preRender(ComponentSystemEvent event) {
// Or in some SystemEvent method (e.g. <f:event type="preRenderView">).
someProperty = loadSomeProperty();
}
public void change(ValueChangeEvent event) {
// Or in some FacesEvent method (e.g. <h:inputXxx valueChangeListener>).
someProperty = loadSomeProperty();
}
public void ajaxListener(AjaxBehaviorEvent event) {
// Or in some BehaviorEvent method (e.g. <f:ajax listener>).
someProperty = loadSomeProperty();
}
public void actionListener(ActionEvent event) {
// Or in some ActionEvent method (e.g. <h:commandXxx actionListener>).
someProperty = loadSomeProperty();
}
public String submit() {
// Or in POST action method (e.g. <h:commandXxx action>).
someProperty = loadSomeProperty();
return "outcome";
}
public SomeObject getSomeProperty() {
// Just keep getter untouched. It isn't intented to do business logic!
return someProperty;
}
}
Note that you should not use bean's constructor or initialization block for the job because it may be invoked multiple times if you're using a bean management framework which uses proxies, such as CDI.
If there are for you really no other ways, due to some restrictive design requirements, then you should introduce lazy loading inside the getter method. I.e. if the property is null, then load and assign it to the property, else return it.
public SomeObject getSomeProperty() {
// If there are really no other ways, introduce lazy loading.
if (someProperty == null) {
someProperty = loadSomeProperty();
}
return someProperty;
}
This way the expensive DB/business logic won't unnecessarily be executed on every single getter call.
See also:
Why is the getter called so many times by the rendered attribute?
Invoke JSF managed bean action on page load
How and when should I load the model from database for h:dataTable
How to populate options of h:selectOneMenu from database?
Display dynamic image from database with p:graphicImage and StreamedContent
Defining and reusing an EL variable in JSF page
Measure the render time of a JSF view after a server request

With JSF 2.0 you can attach a listener to a system event
<h:outputText value="#{ManagedBean.someProperty}">
<f:event type="preRenderView" listener="#{ManagedBean.loadSomeProperty}" />
</h:outputText>
Alternatively you can enclose the JSF page in an f:view tag
<f:view>
<f:event type="preRenderView" listener="#{ManagedBean.loadSomeProperty}" />
.. jsf page here...
<f:view>

I have written an article about how to cache JSF beans getter with Spring AOP.
I create a simple MethodInterceptor which intercepts all methods annotated with a special annotation:
public class CacheAdvice implements MethodInterceptor {
private static Logger logger = LoggerFactory.getLogger(CacheAdvice.class);
#Autowired
private CacheService cacheService;
#Override
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
String key = methodInvocation.getThis() + methodInvocation.getMethod().getName();
String thread = Thread.currentThread().getName();
Object cachedValue = cacheService.getData(thread , key);
if (cachedValue == null){
cachedValue = methodInvocation.proceed();
cacheService.cacheData(thread , key , cachedValue);
logger.debug("Cache miss " + thread + " " + key);
}
else{
logger.debug("Cached hit " + thread + " " + key);
}
return cachedValue;
}
public CacheService getCacheService() {
return cacheService;
}
public void setCacheService(CacheService cacheService) {
this.cacheService = cacheService;
}
}
This interceptor is used in a spring configuration file:
<bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut">
<bean class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut">
<constructor-arg index="0" name="classAnnotationType" type="java.lang.Class">
<null/>
</constructor-arg>
<constructor-arg index="1" value="com._4dconcept.docAdvance.jsfCache.annotation.Cacheable" name="methodAnnotationType" type="java.lang.Class"/>
</bean>
</property>
<property name="advice">
<bean class="com._4dconcept.docAdvance.jsfCache.CacheAdvice"/>
</property>
</bean>
Hope it will help!

Originally posted in PrimeFaces forum # http://forum.primefaces.org/viewtopic.php?f=3&t=29546
Recently, I have been obsessed evaluating the performance of my app, tuning JPA queries, replacing dynamic SQL queries with named queries, and just this morning, I recognized that a getter method was more of a HOT SPOT in Java Visual VM than the rest of my code (or majority of my code).
Getter method:
PageNavigationController.getGmapsAutoComplete()
Referenced by ui:include in in index.xhtml
Below, you will see that PageNavigationController.getGmapsAutoComplete() is a HOT SPOT (performance issue) in Java Visual VM. If you look further down, on the screen capture, you will see that getLazyModel(), PrimeFaces lazy datatable getter method, is a hot spot too, only when enduser is doing a lot of 'lazy datatable' type of stuff/operations/tasks in the app. :)
See (original) code below.
public Boolean getGmapsAutoComplete() {
switch (page) {
case "/orders/pf_Add.xhtml":
case "/orders/pf_Edit.xhtml":
case "/orders/pf_EditDriverVehicles.xhtml":
gmapsAutoComplete = true;
break;
default:
gmapsAutoComplete = false;
break;
}
return gmapsAutoComplete;
}
Referenced by the following in index.xhtml:
<h:head>
<ui:include src="#{pageNavigationController.gmapsAutoComplete ? '/head_gmapsAutoComplete.xhtml' : (pageNavigationController.gmaps ? '/head_gmaps.xhtml' : '/head_default.xhtml')}"/>
</h:head>
Solution: since this is a 'getter' method, move code and assign value to gmapsAutoComplete prior to method being called; see code below.
/*
* 2013-04-06 moved switch {...} to updateGmapsAutoComplete()
* because performance = 115ms (hot spot) while
* navigating through web app
*/
public Boolean getGmapsAutoComplete() {
return gmapsAutoComplete;
}
/*
* ALWAYS call this method after "page = ..."
*/
private void updateGmapsAutoComplete() {
switch (page) {
case "/orders/pf_Add.xhtml":
case "/orders/pf_Edit.xhtml":
case "/orders/pf_EditDriverVehicles.xhtml":
gmapsAutoComplete = true;
break;
default:
gmapsAutoComplete = false;
break;
}
}
Test results: PageNavigationController.getGmapsAutoComplete() is no longer a HOT SPOT in Java Visual VM (doesn't even show up anymore)
Sharing this topic, since many of the expert users have advised junior JSF developers to NOT add code in 'getter' methods. :)

If you are using CDI, you can use Producers methods.
It will be called many times, but the result of first call is cached in scope of the bean and is efficient for getters that are computing or initializing heavy objects!
See here, for more info.

You could probably use AOP to create some sort of Aspect that cached the results of our getters for a configurable amount of time. This would prevent you from needing to copy-and-paste boilerplate code in dozens of accessors.

If the value of someProperty is
expensive to calculate, this can
potentially be a problem.
This is what we call a premature optimization. In the rare case that a profiler tells you that the calculation of a property is so extraordinarily expensive that calling it three times rather than once has a significant performance impact, you add caching as you describe. But unless you do something really stupid like factoring primes or accessing a databse in a getter, your code most likely has a dozen worse inefficiencies in places you've never thought about.

I would also advice using such Framework as Primefaces instead of stock JSF, they address such issues before JSF team e. g in primefaces you can set partial submit. Otherwise BalusC has explained it well.

It still big problem in JSF. Fo example if you have a method isPermittedToBlaBla for security checks and in your view you have rendered="#{bean.isPermittedToBlaBla} then the method will be called multiple times.
The security check could be complicated e.g . LDAP query etc. So you must avoid that with
Boolean isAllowed = null ... if(isAllowed==null){...} return isAllowed?
and you must ensure within a session bean this per request.
Ich think JSF must implement here some extensions to avoid multiple calls (e.g annotation #Phase(RENDER_RESPONSE) calle this method only once after RENDER_RESPONSE phase...)

Related

Infinite recursion in drools after version change from v7.20 to v7.21

When there is a version change in drools-compiler from 7.20.0.Final to 7.21.0.Final some rules are looping recursively.
Code in github:
The working version
The recursively looping version
The change between working and looping version
More details
When I fire a rule whose then part modifies a fact that is already checked in the when part:
rule "rule 1.1"
when
$sampleDomain: SampleDomain(instanceVariable2 == "Value of instance variable")
then
System.out.println("Rule 1.1 fired");
modify($sampleDomain){
setInstanceVariable1(3)
}
end
it doesn't loop recursively.
But when I call another rule which call a static function from another class:
rule "rule 1.2"
when
$sampleDomain: SampleDomain(CoreUtils.anotherFunction())
then
System.out.println("Rule 1.2 fired");
modify($sampleDomain){
setInstanceVariable1(3)
}
end
it loops recursively.
The class with static function is
import com.drool_issue.domain.SampleDomain;
public class CoreUtils {
public static boolean anotherFunction() {
System.out.println("anotherFunction() inside CoreUtils");
return true;
}
public static boolean anotherFunction(SampleDomain sampleDomain) {
System.out.println("anotherFunction(SampleDomain sampleDomain) inside CoreUtils");
return true;
}
}
My domain file is:
public class SampleDomain {
private int instanceVariable1;
private String instanceVariable2;
private int instanceVariable3;
public int getInstanceVariable1() {
return instanceVariable1;
}
public void setInstanceVariable1(int instanceVariable1) {
this.instanceVariable1 = instanceVariable1;
}
public String getInstanceVariable2() {
return instanceVariable2;
}
public void setInstanceVariable2(String instanceVariable2) {
this.instanceVariable2 = instanceVariable2;
}
public int getInstanceVariable3() {
return instanceVariable3;
}
public void setInstanceVariable3(int instanceVariable3) {
this.instanceVariable3 = instanceVariable3;
}
}
This is only caused after version change from 7.20.0.Final to 7.21.0.Final. Any guess on what the problem might be?
When I further looked into the problem I saw this too.
When we add two functions into the SampleDomain class ie
public boolean anotherFunction() {
return true;
}
public boolean anotherFunction(SampleDomain sampleDomain) {
return true;
}
and use this in the rule like:
rule "rule 1.4"
when
$sampleDomain: SampleDomain(anotherFunction())
then
System.out.println("Rule 1.4 fired");
modify($sampleDomain){
setInstanceVariable1(3)
}
end
and
rule "rule 1.5"
when
$sampleDomain: SampleDomain(anotherFunction($sampleDomain))
then
System.out.println("Rule 1.5 fired");
modify($sampleDomain){
setInstanceVariable3(4)
}
end
these also loops recursively.
Code in github:
The recursive looping when using non static methods
The change between working and above version
Also when any of the static method is made non static then method from the domain class is called even though the static method is specified in the rule.
Code portions to be noted here are:
Rule where static method is called.
Another rule which also call the static method.
The static access modifier removed from the functions which where previously static.
Code in github:
Weird behaviour when removing static modifier for the functions.
The change between working and above version
All this are caused in versions after 7.20.0.Final, ie 7.21.0.Final, 7.22.0.Final and 7.23.0.Final
Property reactivity based filtering cannot be applied to external function  since we don't know what the external function (static method) does internally.
To elaborate this:
Let us start with Property reactivity; whenever we use the modify or update keywords in the consequence of a rule, we're notify the engine that rules that filter similar object types should re-evaluate the object again. This re-evaluation, by default, occurs on the whole object. That is as long as one property of the object changes, the rules will consider it as a new object to match. This could lead to some issues when we don't wish to have a rule re-evaluated for some changes. The loop-control mechanisms, such as no-loop and lock-on-active, could be helpful in these situations. However, if we want the rule to control changes on some properties only, we need to write very complex conditions. Also, if the model changes in the future for a large rule base, you may have to modify a lot of rules to avoid undesired rule re-executions. Fortunately, Drools provides a feature that allows the engine to work around this problem. It allows the rule writers to define the attributes of a bean that should be monitored if they're updated in the working memory. This feature can be defined in the data model (both Java classes or declared types) that are used in the rules and it is called property-reactive beans.
To use this feature, we first need to mark the types that we will use in the rules with the Property Reactive annotation. This annotation allows the engine know that whenever an object of this type is added to the working memory, special filtering on its changes needs to apply.  This annotation can be added to a Java class (at class level) or declared type (right after the first line, defining the type name), as follows,
In Java class:
#PropertyReactive public class Customer {     ... }
In declared type:
declare PropertyReactiveOrder
#propertyReactive
discount: Discount
totalItems: Integer
total: Double
end
We can also make all the types property reactive by adding PropertySpecificOption.ALWAYS to builder option.
Note: Property reactive beans changes would be notified to the rule engine only using the modify keyword. The update keyword won't be able to tell the difference between the attributes of the bean that are being changed.
Property reactivity has been introduced in Drools 5.4 but since using this feature is considered a good practice both under correctness and performance points of view, it has been enabled by default in Drools 7.0.
Now once again to our problem, although with property reactivity things have drastically changed and it has been acting like a Fine grained property change listener that allows Drools to understand a little bit more about what is going on inside the RHS of our rules, or at least inside the modify() operation. The functions are still a black box for it, thus creating this problem.

Generic way to initialize a JPA 2 lazy association

So, the question at hand is about initializing the lazy collections of an "unknown" entity, as long as these are known at least by name. This is part of a more wide effort of mine to build a generic DataTable -> RecordDetails miniframework in JSF + Primefaces.
So, the associations are usually lazy, and the only moment i need them loaded is when someone accesses one record of the many in the datatable in order to view/edit it. The issues here is that the controllers are generic, and for this I also use just one service class backing the whole LazyLoading for the datatable and loading/saving the record from the details section.
What I have with come so far is the following piece of code:
public <T> T loadWithDetails(T record, String... associationsToInitialize) {
final PersistenceUnitUtil pu = em.getEntityManagerFactory().getPersistenceUnitUtil();
record = (T) em.find(record.getClass(), pu.getIdentifier(record));
for (String association : associationsToInitialize) {
try {
if (!pu.isLoaded(record, association)) {
loadAssociation(record, association);
}
} catch (..... non significant) {
e.printStackTrace(); // Nothing else to do
}
}
return record;
}
private <T> void loadAssociation(T record, String associationName) throws IntrospectionException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
BeanInfo info = Introspector.getBeanInfo(record.getClass(), Object.class);
PropertyDescriptor[] props = info.getPropertyDescriptors();
for (PropertyDescriptor pd : props) {
if (pd.getName().equals(associationName)) {
Method getter = pd.getReadMethod();
((Collection) getter.invoke(record)).size();
}
}
throw new NoSuchFieldException(associationName);
}
And the question is, did anyone start any similar endeavor, or does anyone know of a more pleasant way to initialize collections in a JPA way (not Hibernate / Eclipselink specific) without involving reflection?
Another alternative I could think of is forcing all entities to implement some interface with
Object getId();
void loadAssociations();
but I don't like the idea of forcing my pojos to implement some interface just for this.
With the reflection solution you would suffer the N+1 effect detailed here: Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans
You could use the OpenSessionInView instead, you will be affected by the N+1 but you will not need to use reflection. If you use this pattern your transaction will remain opened until the end of the transaction and all the LAZY relationships will be loaded without a problem.
For this pattern you will need to do a WebFilter that will open and close the transaction.

Pass arguments to a number of PresenterWidget in GWTP

I have a GWTP Presenter in which I want to add an undetermined number of instances of GWTP PresenterWidget. To each of that instances I need to pass an argument (a different argument to each instance) that the parent Presenterowns.
There are two things that I need to accomplish here:
1. Instantiate an undetermined number of PresenterWidget
Reading here, it looks like I just need a Provider.
2. Transfer to each of those PresenterWidget the argument I want.
ProxyEvent does not seem an option since the PresenterWidget has no proxy
I need to pass the argument before revealing the PresenterWidget
Is it possible or is it a good practice to just declare a public method on the PresenterWidget and access it from the parent presenter?
For example:
public class MyWidgetPresenter extends PresenterWidget<MyWidgetPresenter.MyView> {
...
private MyArgument argument;
public void setArgument(MyArgument argument){
this.argument=argument;
}
And then the Parent presenter could:
#Inject Provider<MyWidgetPresenter> myWidgetPresenterProvider;
...
[this could be part of a loop]
MyWidgetPresenter myWidgetPresenter = myWidgetPresenterProvider.get();
myWidgetPresenter.setArgument(argument);
getView().addToSlot(SLOT_MyWidgetPresenters, myWidgetPresenter);
[loop end]
Is this a valid solution at all? I have implemented it and everything works except that my PresenterWidget never calls onReveal or onReset which prevents to show the content. Any ideas why?
There are different ways to solve this problem, one of them is the way you showed in your own answer.
create a setter on your PresenterWidget and set it from your parent Presenter (how you have done it).
Fire an Event on the EventBus and handle it in your PresenterWidgets (The event contains the EntryProxy instance).
Let the PresenterWidget itself retrieve the data from the backend.
Solution 3 won't work in your case because you have not a single PresenterWidget but as many as you have data.
Solution 2 has the least coupling. However when you use PresenterWidgets you have anyways a coupling between your parent Presenter and your PresenterWidget so there is not much benefit. I would only use this method if you want to use your retrieved EntityProxy elswhere (i.e. breadcrumb PresenterWidget).
Solution 1 (the one you suggested) is fine if you only deal with the EntryProxy in those PresenterWidgets.
I am answering this since I found where the problem is. Still I don't know if what I am doing is considered a good practice. [See Ümit's answer]
The reason why my WidgetPresenter was not calling onReveal() or onReset() was because I was calling the view's setInSlot, instead of the Presenter. This can be an easy mistake.
On your presenter never do this:
getView().setInSlot(whatever,whatever)
But rather
[this.] setInSlot(whatever,whatever)
Here is my code, for completeness sake:
The parent Presenter:
#Override
public void onReset(){
super.onReset();
/* Request the Topic graph to show using RequestFactory*/
TopicService service = requestFactory.topicService();
service.getTopicGraph(movieId).with("entries").fire(new Receiver<TopicProxy>(){
#Override
public void onSuccess(TopicProxy response) {
/* Clear whatever was in the slot before */
getView().setInSlot(null, null);
/* Get the Topic and set the title in this Presenter*/
topic = response;
getView().setMovieTitle(topic.getName());
/* Then:
* - retrieve the Entries and add them to as many PresenterWidgets as needed
* - add those widgets to an slot on this Presenter
* - set on the PresenterWidget the Entry, that call also set's the child's view*/
Iterator<EntryProxy> it = topic.getEntries().iterator();
while(it.hasNext()){
//TODO: pagination
ReviewPresenter myRP = myReviewPresenterProvider.get();
myRP.setEntry(it.next());
setInSlot(SLOT_movie, myRP);
reviewPresenterList.add(myRP);
}
}
#Override
public void onFailure(ServerFailure error){
getView().setMovieTitle(error.getMessage());
//TODO use a label or go to error Place
}
});;
And the setEntry method on the PresenterWidget:
public void setEntry(EntryProxy entry){
this.entry = entry;
getView().setTextArea(entry.getText());
}

Should a method be 'fired' from within a property?

My application uses the MVVM pattern. My TextBox is bound to a property of my ViewModel (type string).
When ever the content of the TextBox changed via the user typing, I want to perform some validation.
So, currently, my code is
<TextBox Text="{Binding XmlContentAsString, UpdateSourceTrigger=PropertyChanged}" />
and my ViewModel has this property and field:
private string _xmlContentAsString;
public string XmlContentAsString
{
get { return _xmlContentAsString; }
set
{
if (_xmlContentAsString == value)
return;
_xmlContentAsString = value;
PerformValidiationLogic(value);//This is where I am unsure
}
}
Now, this works but, and I don't know why, I don't like this! It some how feels 'hacked' to include the method in the property.
Can some one please tell me if this is the correct approach when using the MVVM pattern?
There's different type of validations.
For simplistic validating string lengths or allowed characters etc you can use DataAnnotations and put the validation in attributes on your properties. You'll need to include
using System.ComponentModel.DataAnnotations;
then for example to keep string to 9 characters:
[StringLength(9)]
public string StringValue
{
get
{
return stringValue;
}
set
{
this.stringValue = value;
}
}
Then there is validation that is a bit more complex and is effectively enforcing your business logic.
There seem to be many views on how to do this. Ideally it should belong on the model, so that the validation can be reused, but obviously called via the viewmodel.
Personally I will put method calls in the property setters occasionally, to me thats the whole reason for having the ability to create setters and getters - otherwise there's very little point in having anything other than auto properties.
But if it's complex or asynchronous then you can hit issues.
I'd be very careful doing it with UpdateSourceTrigger=PropertyChanged, as that means you'll be firing it every character.
In your example, you perform validation logic on the value, but what would be the result of the validation if it fails? Typically you would want to notify the user of a validation failure. If that is the case, then I suggest IDataErrorInfo (examples can be found here:
http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/).
If you plan on overriding the value without notifying the user, then validating in the setter is acceptable (though still not a fan for more personal reasons).
In my opinion thats the correct approach. I would write a base class for your ViewModel that contains a method that sets the property, call PropertyChanged and validate if some validation rule is attached to that property.
For example:
public abstract class ValidableViewModel
{
private List<ValidationRule> _validationRules;
public ValidableViewModel()
{
_validationRules = new List<ValidationRule>();
}
protected virtual void SetValue<T, T2>(Expression<Func<T>> expression,
ref T2 backend, T2 value)
{
if (EqualityComparer<T2>.Default.Equals(backend, value))
return;
backend = value;
OnPropertyChanged(expression);
Validate(expression.Name, value);
}
protected void Validate(string propertyName, object value)
{
foreach(var validationRule in _validationRules)
{
if(validationRule.PropertyName == propertyName)
validationRule.Execute(value);
}
}
}
The code is not complete, there is missing a lot. But it could be a start ;-)
I personally don't advise putting so much logic in your property. I would use a command bound to an event, ie the lostfocus event of the textbox, and perform your validation there.
I would use something like this:
<TextBox Text="{Binding XmlContentAsString, UpdateSourceTrigger=PropertyChanged}">
<interactivity:Interaction.Triggers>
<interactivity:EventTrigger EventName="LostFocus">
<interactivity:InvokeCommandAction Command="{Binding LostFocusCommand, Mode=OneWay}"/>
</interactivity:EventTrigger>
</interactivity:Interaction.Triggers>
</TextBox>
then have a command in your view model that is LostFocusCommand wiht your validation logic.
I use mvvm-light and can give a more detailed example for that. (you will need to include the blend interactivity declaration at the top of your xaml)

Unit testing with EF Code First DataContext

This is more a solution / work around than an actual question. I'm posting it here since I couldn't find this solution on stack overflow or indeed after a lot of Googling.
The Problem:
I have an MVC 3 webapp using EF 4 code first that I want to write unit tests for. I'm also using NCrunch to run the unit tests on the fly as I code, so I'd like to avoid backing onto an actual database here.
Other Solutions:
IDataContext
I've found this the most accepted way to create an in memory datacontext. It effectively involves writing an interface IMyDataContext for your MyDataContext and then using the interface in all your controllers. An example of doing this is here.
This is the route I went with initially and I even went as far as writing a T4 template to extract IMyDataContext from MyDataContext since I don't like having to maintain duplicate dependent code.
However I quickly discovered that some Linq statements fail in production when using IMyDataContext instead of MyDataContext. Specifically queries like this throw a NotSupportedException
var siteList = from iSite in MyDataContext.Sites
let iMaxPageImpression = (from iPage in MyDataContext.Pages where iSite.SiteId == iPage.SiteId select iPage.AvgMonthlyImpressions).Max()
select new { Site = iSite, MaxImpressions = iMaxPageImpression };
My Solution
This was actually quite simple. I simply created a MyInMemoryDataContext subclass to MyDataContext and overrode all the IDbSet<..> properties as below:
public class InMemoryDataContext : MyDataContext, IObjectContextAdapter
{
/// <summary>Whether SaveChanges() was called on the DataContext</summary>
public bool SaveChangesWasCalled { get; private set; }
public InMemoryDataContext()
{
InitializeDataContextProperties();
SaveChangesWasCalled = false;
}
/// <summary>
/// Initialize all MyDataContext properties with appropriate container types
/// </summary>
private void InitializeDataContextProperties()
{
Type myType = GetType().BaseType; // We have to do this since private Property.Set methods are not accessible through GetType()
// ** Initialize all IDbSet<T> properties with CollectionDbSet<T> instances
var DbSets = myType.GetProperties().Where(x => x.PropertyType.IsGenericType && x.PropertyType.GetGenericTypeDefinition() == typeof(IDbSet<>)).ToList();
foreach (var iDbSetProperty in DbSets)
{
var concreteCollectionType = typeof(CollectionDbSet<>).MakeGenericType(iDbSetProperty.PropertyType.GetGenericArguments());
var collectionInstance = Activator.CreateInstance(concreteCollectionType);
iDbSetProperty.SetValue(this, collectionInstance,null);
}
}
ObjectContext IObjectContextAdapter.ObjectContext
{
get { return null; }
}
public override int SaveChanges()
{
SaveChangesWasCalled = true;
return -1;
}
}
In this case my CollectionDbSet<> is a slightly modified version of FakeDbSet<> here (which simply implements IDbSet with an underlying ObservableCollection and ObservableCollection.AsQueryable()).
This solution works nicely with all my unit tests and specifically with NCrunch running these tests on the fly.
Full Integration Tests
These Unit tests test all the business logic but one major downside is that none of your LINQ statements are guaranteed to work with your actual MyDataContext. This is because testing against an in memory data context means you're replacing the Linq-To-Entity provider but a Linq-To-Objects provider (as pointed out very well in the answer to this SO question).
To fix this I use Ninject within my unit tests and setup InMemoryDataContext to bind instead of MyDataContext within my unit tests. You can then use Ninject to bind to an actual MyDataContext when running the integration tests (via a setting in the app.config).
if(Global.RunIntegrationTest)
DependencyInjector.Bind<MyDataContext>().To<MyDataContext>().InSingletonScope();
else
DependencyInjector.Bind<MyDataContext>().To<InMemoryDataContext>().InSingletonScope();
Let me know if you have any feedback on this however, there are always improvements to be made.
As per my comment in the question, this was more to help others searching for this problem on SO. But as pointed out in the comments underneath the question there are quite a few other design approaches that would fix this problem.