Lambda parameter not working in Moq - moq

I keep getting the "Unsupported expression" exception. It seems that the lambda expression (a=>a.PP_EventID==1) is the problem. How do solved this one?
pricepackPersistenceMock.Setup(pricepack => pricepack.Delete(a=>a.PP_EventID==1)).Verifiable();

You should use the predicate inside It.Is<T>() method.
pricepackPersistenceMock.Setup(pricepack => ricepack.Delete(It.Is<TypeOfa>(a=>a.PP_EventID==1)))
.Verifiable();
Update:
eventPersistenceMock.Setup(u => u.Single(It.IsAny<Func<tbl_SBAem_Event, bool>>()))
.Returns(eventlists.Where(a => a.EventMngID == currentevent.EventMngID).Single());
// you can directly return the value
//verifiable is not needed because you set the return value

Related

Is it possible to both dispatch an array of actions and also navigate from an ngrx effect?

I have an issue with one of my application's ngrx effects. I am basically trying to execute multiple actions using concatMap() AND navigate using the router store's go().
Here is the effect:
#Effect()
loadPersonalInfoAndSignin$: Observable<Action> = this.actions$
.ofType(session.ActionTypes.LOAD_PERSONAL_INFO)
.map((action: LoadPersonalInfoAction) => action.payload)
.do(sessionToken => {
localStorage.setItem('authenticated', 'true');
localStorage.setItem('sessionToken', sessionToken);
})
.switchMap(() => this.userAccountService
.retrieveCurrentUserAccount()
.concatMap(currentUserAccount => [
new LoadUserAccountAction(currentUserAccount),
new SigninAction(),
new LoadMessagesAction({})
])
)
.mapTo(go(['/dashboard']));
If I remove the .mapTo(go(['/dashboard'])), then all three actions in the concatMap array are successfully dispatched to their corresponding effects.
I am therefore wondering why my mapTo(go(... is causing the last two actions in the array (i.e. SigninAction & LoadMessagesAction) not to be dispatched to their corresponding effects..
Can someone please help?
edit: Changing mapTo to do as follows:
.do(go(['/dashboard']));
results in the following error:
ERROR in /Users/julien/Documents/projects/bignibou/bignibou-client/src/app/core/store/session/session.effects.ts (55,9): Argument of type 'Action' is not assignable to parameter of type 'PartialObserver<SigninAction>'.
Type 'Action' is not assignable to type 'CompletionObserver<SigninAction>'.
Property 'complete' is missing in type 'Action'.
Using do for the go call will not see the route changed. go is an action creator and the action that it creates needs to be emitted from the effect for #ngrx/router-store to receive the action and effect the route change.
Also, the mapTo operator will ignore what it receives and will emit the value you've specified, so it's not appropriate, either.
Instead, you should include the action created by the go call in your concatMap array:
#Effect()
loadPersonalInfoAndSignin$: Observable<Action> = this.actions$
.ofType(session.ActionTypes.LOAD_PERSONAL_INFO)
.map((action: LoadPersonalInfoAction) => action.payload)
.do(sessionToken => {
localStorage.setItem('authenticated', 'true');
localStorage.setItem('sessionToken', sessionToken);
})
.switchMap(() => this.userAccountService
.retrieveCurrentUserAccount()
.concatMap(currentUserAccount => [
new LoadUserAccountAction(currentUserAccount),
new SigninAction(),
new LoadMessagesAction({}),
go(['/dashboard'])
])
);

Why Include() not available when Single() is used in entity framework code first fluent api

I wonder why Include() cannot be used after Single() in eager-loading. For example, in the following snippet, Include is not available:
db.Teachers.Single(p => p.Id == currUserId)
.Include(t => t.OfferedCourses)
.RegisteredCourses
.ToList();
However, it would work if I have Single() just after Include():
db.Teachers.Include(t => t.OfferedCourses)
.Single(p => p.Id == currUserId)
.RegisteredCourses
.ToList();
This way, many unnecessary related data will be returned. The following is the method I ended up with:
db.Teachers.Where(p => p.Id == currUserId)
.Include(t => t.OfferedCourses)
.First()
.RegisteredCourses
.ToList();
Is this the only solution?
The following is an answer to your question from the title of the post:
Why Include() not available when Single() is used in entity framework code first fluent api
.Include() is an extension method in Linq-To-Entities that expects type IQueryable.
When you specify db.Teachers.Include() or db.Teacher.Where().Include() you are satisfying this requirement because both db.Teachers and db.Teachers.Where() return type IQueryable.
But when you specify db.Teachers.Single() that returns type Teacher which won't work for the use of Include().

"This value is not valid" when using "query_builder" on "entity" buildForm on symfony2.1

Here is my problem.
I use the buildForm method on symfony 2.1 in order to build my form.
With the following code everything works just fine :
$builder->add('combat','entity',array(
class' => 'KarateCompetitionBundle:CompetitionCombat',
'empty_value' => 'Sélectionner un combat'));
But I want to filter and display only some Combat. That's why I have to use the query_builder option. When i do that i get the This value is not valid error message.
Here is the code :
$builder->add('combat','entity',array(
'class' => 'KarateCompetitionBundle:CompetitionCombat',
'empty_value' => 'Sélectionner un combat',
'query_builder' => function(CombatRepository $cr) {
return $cr->getAllWithoutBilanQueryBuilder();}));
I reduce at the minimum the code (i.e. no filtering on the getAllWithoutBilanQueryBuildermethod) in order to be able to find the problem.
public function getAllWithoutBilanQueryBuilder(){
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
return $queryBuilder->select('c')->from('KarateEntrainementBundle:CompetitionCombat', 'c');
}
I've compared both html code generate on each case and they are the same.
I put a var_dump($object) on the controller after binding the form with the request $form->bind($request) and it appears that when i use the query_builder option the combatis null while it is not null if i don't use it.
I can't manage to understand why ?
I found few post on the web with the same issue but none with an answer.
Is it possible that there is a symfony issue here or am I doing something wrong ?
I had the exact same problem and - in my case - traced it back to Symfony\Bridge\Doctrine\Form\ChoiceList\ORMQueryBuilderLoader.
When the form is validated, the entities are loaded by primary key in ORMQueryBuilderLoader::getEntitiesByIds() by adding an IN() clause to the query builder. In my case, this IN() clause was ineffective and all selectable entities were returned.
This, in turn, caused Symfony\Component\Form\Extension\Core\DataTransformer\ChoicesToValuesTransformer::reverseTransform() to throw a TransformationFailedException, because the number of loaded entities and submitted choices were not the same.
I suppose there's other possible causes for this specific error. Here's what you could try:
Look at the generated query, run it manually and make sure it returns only the selected values
In Symfony\Component\Form\Form, try outputting the caught TransformationFailedException and see where it leads you.
If none of the above seem plausible, add some debug output to Symfony\Component\Form\Extension\Validator\Constraints\FormValidator and see whether you can narrow it down somewhat.
As an addition to #mike-b answer: for me failing QueryBuilder statement was ->having('...') query part:
...
'query_builder' => function(EntityRepository $er) use ($pn) {
return $er->createQueryBuilder('p')
->select('p')
->join('p.product', 'pr')
->where('p.name = ' . $pn->getId())
->andWhere("LENGTH(p.value_en) > 1")
->andWhere("p.value_en != ''")
/* when I remove this - validation passe flawlessly */
->having('COUNT(pr.id) > 1')
->groupBy('p.value_en)
->orderBy('p.value_en', 'ASC');
...
tested with Symfony version 2.3.6
I finally managed to make this worked :-)
So here was the fix.
On the getAllWithoutBilanQueryBuilder function, I replace
$queryBuilder = $this->getEntityManager()->createQueryBuilder();
by
$queryBuilder = $this->createQueryBuilder('c');
I don't know what is exactly the difference and why this is now working.
But this is working.
Thanks you all for your help.

Illegal offset type in isset or empty in EntityChoiceList.php line 273

Within my Symfony2 project I've attempted to dynamically generate the entities used within my form type, by-passing the use of query builder etc.
To he entity choices property I am supplying an array of entities to be used. On page load everything seems fine and the correct content is displayed. However on form submission I get
Illegal offset type in isset or empty in EntityChoiceList.php line 273
at ErrorHandler ->handle ('2', 'Illegal offset type in isset or empty',
'..../Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php', '273', array('key' => object(myEntity))) in ..../Symfony/Bridge/Doctrine/Form/ChoiceList/EntityChoiceList.php at line 273
.....
return isset($entities[$key]) ? $entities[$key] : null;
.....
What has me stumped is if I add var_dump(isset($this->entities[$key]));exit; above this line I am returned 'bool(true)' which to me means the key does exist.
As background I have attempted to extend the EntityType, for ease within my project and added:
public function getDefaultOptions(array $options)
{
$defaultOptions = array(
'em' => null,
'class' => 'Acme\TestBundle\Entity\myEntity',
'property' => null,
'query_builder' => null,
'choices' => $this->myEntityArray,
);
$options = array_replace($defaultOptions, $options);
$defaults = parent::getDefaultOptions($options);
return $defaults;
}
Has any one any ideas why I getting this error, or am I going about my issue all wrong anyway, with trying to pass an array of entities to choices?
If you're getting this while trying to remove an element from an ArrayCollection it's probably because you've typed:
$list->remove($item) instead of $list->removeElement($item)
I'm guessing you already solved this some other way, and this isn't a real answer either.
But I'm guessing either $entities isn't an array on that point, or $key isn't a scalar value.
For debugging you should use:
<?php
if (!is_array($entities) || !is_scalar($key)) {
var_dump($key, $entities));exit;
}
How you now tested this, it would stop on the first pass in that function. Symfony Forms use quit a lot of recursion, so an exit in any function usually doesn't help you.

comparing a DateTime in CakePHP

I have a query in CakePHPthat has a stored "datetime" field called DropIn.drop_in_time. I would like to only "find" entries where the DropIn.drop_in_time is > NOW() but am having trouble getting it to do that.
The condition DropIn.drop_in_time >' => 'NOW() didn't get the right results in the query below. Is there a better way to do it?
$requests = $this->DropIn->find('all', array(
'conditions' => array('DropIn.drop_in_time >' => 'NOW()', 'or' => array(array('DropIn.user_id' => $this->Auth->user('id')), array('DropIn.id' => $drop_in_ids))),
'order'=>array('DropIn.created'=>'DESC')));
If you separate the value as 'DropIn.drop_in_time' => 'NOW()', 'NOW()' is taken to mean the literal value string "NOW()". Just write it as one SQL fragment instead: 'DropIn.drop_in_time > NOW()'. Alternatively, use 'DropIn.drop_in_time >' => date('Y-m-d H:i:s').
If you really want to put DB expressions into CakePHP finds, you can use the expression method:
'DropIn.drop_in_time.' => $db->expression('CURDATE()');
However this is kinda of losing the point of the database abstraction that a framework provides, so do as suggested by deceze and compare it with date('Y-m-d H:i:s')
use DboSource::expression('NOW') instead of only NOW()

Resources