Why is this Repository Method not working? - typo3-flow

I used this Repository Method in an Extbase Project and it worked fine.
public function findRandom() {
$rows = $this->createQuery()->execute()->count();
$row_number = mt_rand(0, max(0, ($rows - 1)));
return $this->createQuery()->setOffset($row_number)->setLimit(1)->execute();
}
It is not working in TYPO3 Flow. Why? And what should I change?

Sound strange Flow must return an object in this, like Extbase does, or in your case an QueryResultInterface of one object, if you need directly an object, you can use this kind of code:
$query->execute()->getFirst();
Hope that help,

I did not mention, the queryResult is not the object it self. Its an array. My code above is working.
This is a difference between extbase and flow3. Flow3 returns an array. Extbase the object itself.

Related

What is the proper syntax to chain multiple queries together?

I'm using the HotTowel SPA template which makes use of Durandal. In my Durandal ViewModels I am using Breeze to get some data from the database.
I have a datacontext class that I put all my breeze queries in and the queries all follow the pattern like the following:
getAthletes: function (queryCompleted) {
var query = breeze.EntityQuery.from("Athletes");
return manager
.executeQuery(query)
.then(queryCompleted)
.fail(queryFailed)
}
Since I'm doing an asynchronous call in the activate method of the view model, I have to return the promise that comes back from these calls in the activate method.
Using a single query works great like this:
function activate() {
datacontext.getAthlete(loadAthlete);
}
However, if I need to perform two queries I run into problems, but only in the release version of my application. I have tried doing this with the following syntax:
function activate() {
datacontext.getAthlete(loadAthlete).then(datacontext.getOtherData(loadOtherData));
}
This will work fine in debug mode, but when I deploy it out to the server and my scripts get bundled, I get an exception which isn't very clear.
t is not a function
I've also tried chaining them together in my datacontext class like below, but I still get the same error.
getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
var athleteQuery = breeze.EntityQuery.from("Athletes").where("id", "==", athleteId);
var effortsQuery = breeze.EntityQuery.from("BestEfforts").where("athleteId", "==", athleteId);
return manager.executeQuery(athleteQuery).then(athleteQueryCompleted)
.then(manager.executeQuery(effortsQuery).then(effortsQueryCompleted))
.fail(queryFailed);
}
So I'm assuming I just don't understand the Q.defer() enough to use it properly or there is something else going on.
What is the correct syntax to accomplish this?
Ok, thanks to RainerAtSpirit for pointing me in the right direction to find this. I looked at John Papa's jumpstarter examples and he has a datacontext that does this under the primeData function.
So using the syntax he used there I was able to get it to work correctly like this:
getAthleteAndEfforts: function (athleteId, athleteQueryCompleted, effortsQueryCompleted) {
return Q.all([
datacontext.getAthlete(athleteId, athleteQueryCompleted),
datacontext.getAthleteEfforts(athleteId, effortsQueryCompleted)]);
}
I had seen the Q.all in the Q documentation but wasn't sure how to use it, but this example helped. I tested this and it works both in debug and release modes.
Not sure why the first version is working at all, but you'd return a promise when datacontext is making async calls.
function activate() {
return datacontext.getAthlete(loadAthlete);
}
or
function activate() {
return datacontext.getAthlete(loadAthlete).then( return datacontext.getOtherData(loadOtherData));
}
Check #John Papa's jumpstarter for more examples: https://github.com/johnpapa/PluralsightSpaJumpStartFinal/search?q=activate

c# library or helper for object mapping / copying in update operations in RavenDB?

Perhaps I'm not going about this the right way, so if anyone can steer me in the right direction, I would greatly appreciate it.
I have a lot of methods in my code that do something like
void UpdateWidget(Widget updatedWidget)
{
IDocumentSession session = documentStore.OpenSession();
oldWidget = session.Load<Widget>("widgets" + widget.Id);
oldWidget.Name = updatedWidget.Name;
oldWidget.Color = updatedWidget.Color;
oldWidget.CreatedDateTime = updatedWidget.CreatedDateTime;
session.SaveChanges();
}
What I'd LIKE to do is something like the following (assuming the IDs are the same of course)
void UpdateWidget(Widget updatedWidget)
{
IDocumentSession session = documentStore.OpenSession();
oldWidget = session.Load<Widget>("widgets" + widget.Id);
oldWidget = updatedWidget
session.SaveChanges();
}
Can someone help me with some syntax or pattern that can get me close to this? Is there a way to use object tracking in Raven to accomplish this? Or do I need some sort of mapping tool like automapper (which I don't understand very well)
thanks in advance!
You can just store the updated object and it will replace the old one if it exists already.
void UpdateWidget(Widget updatedWidget)
{
using (var session = documentStore.OpenSession())
{
session.Store(updatedWidget);
session.SaveChanges();
}
}
However, you have to consider the concurrency effects.
If you have optimistic concurrency disabled, it should just accept the new document, but you risk stepping on others changes. If you have it enabled, you need to either do the Load and update in the same session, or you need to track the etag of the document yourself.
Review the following RavenDB knowledge base article for details: http://ravendb.net/kb/16/using-optimistic-concurrency-in-real-world-scenarios
ALSO - not related to your question, but it's very important that your session is being disposed properly. Wrap it in a using statement. (Or if it's being injected, then make sure your IoC has the appropriate lifetime scope and is disposing it when appropriate.)
AutoMapper or similar (Value Injecter) is ideal for getting rid of code mapping from one object to another.
Using AutoMapper, you would replace
oldWidget.Name = updatedWidget.Name;
oldWidget.Color = updatedWidget.Color;
oldWidget.CreatedDateTime = updatedWidget.CreatedDateTime;
with
AutoMapper.Mapper.CreateMap<Widget, Widget>();
var oldWidget = AutoMapper.Mapper.Map<Widget, Widget>(updatedWidget);
AutoMapper (.CreateMap) should be configured in the application startup.

How to get TotalRows Count in Breezejs, so that I can do paging

I am using Breezejs for client JavaScript. I am not sure how to get the Total count of query when using Breezejs (server side using IQueryable) that has filters (where clause) applied.
As of v 0.75.1 we have added a new 'inlineCount' method to the EntityQuery. Please see the breeze API docs for more details. Hopefully, this will provide what you need.
We made a little change to Ward's solution, because Enumerable.Count loads all records from db, not only count (we realized this after watching sql profiler).
First we create a wrapper for IQueryable.Count extension method (because we cannot call an extension method via reflection).
public static class QueryWrapper {
public static int Count<T>(IQueryable<T> query) where T: class {
return query.Count();
}
}
and we changed
if (actionExecutedContext.Request.RequestUri.Query.Contains("$inlinecount")) {
if (dQuery is IQueryable) {
inlineCount = Enumerable.Count(dQuery);
}
}
with this code,
if (actionExecutedContext.Request.RequestUri.Query.Contains("$inlinecount")) {
if (dQuery is IQueryable) {
var method = typeof(QueryWrapper).GetMethod("Count");
var genericMethod = method.MakeGenericMethod(elementType);
inlineCount = (int)genericMethod.Invoke(null, new object[] { dQuery });
}
}
after this change, Entity Framework gets only count, not all records.
Hope this helps.
Have a nice day.
Support $inlinecount in queries currently is under review - please vote for it.
UPDATE: $inlineCount is in Breeze as of v.0.75.1, rendering this answer obsolete.
Accordingly, I have deleted my answer which described a workaround (a workaround improved by Umut Özel in his answer here). The new feature was driven by this S.O. question and all of your contributions. Thank you.

StructureMap 202 - Why?

OK, I'm trying to set a property on a type I'm registering with SM.
Here's the code from the registry in one of my components. This
registry is being added during the configuration from a console app.
When I try to access the EndorsementSpecs property of the instance
AutoMandatoryEndorsementAggregator object, I get the 202. What's
interesting is that I can call
GetAllInstances>() from my
console app and it resolves just fine. Is there something about
accessing this code from within OnCreation that is causing the 202? I
can see everything I expect in WhatDoIHave(). I've also tried a TypeInterceptor with the same results.
//register all open generics
cfg.ConnectImplementationsToTypesClosing(typeof
(MandatoryEndorsementSpecBase<>));
ForSingletonOf<IMandatoryEndorsementAggregator<AutoPolicy>>()
.Use<AutoMandatoryEndorsementAggregator>()
.OnCreation((context, x) =>
{
var specs =
context.GetAllInstances<MandatoryEndorsementSpecBase<AutoPolicy>>();
x.EndorsementSpecs = specs;
})
;
Sorry to deflect your real questions, but are you just trying to inject all instances of MandatoryEndorsementSpecBase into AutoMandatoryEndorsementAggregatory?
If so, you can probably get away with just making it a constructor parameter so that they are all automatically injected.
public AutoMandatoryEndorsementAggregatory(MandatoryEndorsementSpecBase<AutoPolicy>[] endorsementSpecs){
EndorsementSpecs = endorsementSpecs;
}

How to check if two objects are of the same type in Actionscript?

I want to do this in Actionscript:
typeof(control1) != typeof(control2)
to test if two objects are of the same type. This would work just fine in C#, but in Actionscript it doesnt. In fact it returns 'object' for both typeof() expressions because thats the way Actionscript works.
I couldn't seem to find an alternative by looking in the debugger, or on pages that describe typeof() in Actionscript.
Is there a way to get the actual runtime type?
The best way is to use flash.utils.getQualifiedClassName(). Additionally, you can use flash.utils.describeType() to get an XML document the describes more about the class.
Actionscript 3 has an is operator which can be used to compare objects. Consider the following code:
var mySprite:Sprite = new Sprite();
var myMovie:MovieClip = new MovieClip();
trace(mySprite is Sprite);
trace(myMovie is MovieClip);
trace(mySprite is MovieClip);
trace(myMovie is Sprite);
Which will produce the following output:
true
true
false
false
This will work for built-in classes, and classes you create yourself. The actionscript 2 equivalent of the is operator is instanceof.
You'll want to use the Object.prototype.constructor.
From the documentation:
dynamic class A {}
trace(A.prototype.constructor); // [class A]
trace(A.prototype.constructor == A); // true
var myA:A = new A();
trace(myA.constructor == A); // true
(Conveniently, this is also how to check types in javascript, which is what originally led me to this in the docs)
So, to test this out before I posted here, I tried it in an app I have, in a class called Player. Since the prototype property is static, you can't call it using "this" but you can just skip the scope identifier and it works:
public function checkType():void {
trace(prototype.constructor, prototype.constructor == Player);
// shows [class Player] true
}
Is there a way to get the actual runtime type?
Yes.
var actualRuntimeType:Class = Object(yourInstance).constructor;
Some other answers already refer to .constructor, but you can't always directly access .constructor in ActionScript 3. It is only accessible on dynamic classes, which most classes are not. Attempting to use it on a regular class will cause a compile-time error under the default settings.
However, because every class inherits from Object, which is dynamic, we can look up their .constructor property just by casting an instance to Object.
Therefore if we are not interested in subclasses, we can confirm that two instances are of exactly the same class by simply evaluating this:
Object(instanceA).constructor === Object(instanceB).constructor;
I learned of this from the post "Get the class used to create an object instance in AS3" by Josh Tynjala.
A even simpler alternative that also works for me is just:
var actualRuntimeType:Class = yourInstance["constructor"];
The runtime is entirely capable of giving you the .constructor, it's just that the compiler complains if you use that syntax. Using ["constructor"] should produce the same bytecode, but the compiler isn't clever enough to stop you.
I included this second because it hasn't been tested anywhere except my current Flash environment, whereas several users have said that the method described above works for them.
If you want to account for inheritance, then you might want to try something like this:
if (objectA is objectB.constructor || objectB is objectA.constructor)
{
// ObjectA inherits from ObjectB or vice versa
}
More generally, if you want to test whether objectA is a subtype of objectB
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
...
if (objectA is getDefinitionByName(getQualifiedClassName(objectB)))
{
...
}
Object obj = new Object();
Object o = new Object();
if(o.getClass().getName().endsWith(obj.getClass().getName())){
return true;
}else{
return false;
}

Resources