Flex: Updating data provider of mx:tree - actionscript-3

I create a mx:tree with flex and its data provider is an array collection. In addition, this array collection is set by using a database. This process is handled with an event listener function. Database returns data to array collection asynchronously. And this is the problem that when flex application is started array collection is not fully initialized. Hence, mx:tree is incomplete. Here is the code segment:
protected function populateTreeNode(node:Object):void
{
if (node != null && node["className"] != "InventoryCategory") return;
var categoryId:Number = 0;
if (node != null)
categoryId = node["id"];
DAOUtil.loadAll("InventoryCategory", EventUtil.handleWithArgs(popoluateTreeNodeHandler, [node, "InventoryCategory"]), "categoryId", categoryId.toString());
DAOUtil.loadAll("InventoryItem", EventUtil.handleWithArgs(popoluateTreeNodeHandler, [node, "InventoryItem"]), "categoryId", categoryId.toString());
}
protected function popoluateTreeNodeHandler( event : Event , nodeCategory:Object, typeName:String): void
{
var items:Array = DAOUtil.getArray(event, typeName);
items = LangUtil.fromNameField(items);
if (nodeCategory != null)
nodeCategory["children"] = items;
else
inventoryArray.addAll(new ArrayCollection(items));
for each (var item:Object in items) populateTreeNode(item);
}
This function tries to initialize array collection recursively and at the end of the populateTreeNodeHandler function it is fully initialized. But when flex application is started, it is sometimes incomplete. Is there any solution to this problem?

Problem is fixed. Problem is the fulfilling the data provider array two times. One of them fulfill the array with category items correctly but the other one empty the data provider array.

Related

call object method instead of global method in js new Function

i try make editor that allow user attach function to dynamic objects
each object have init method, allow user attach some actions on user input
think about this
user select baby and write in textarea
move(1)
then select tank and insert in text area
onEnter(){
fire(1)
}
we have baby and tank and some other dynamic objects
i pass code from text area to each object initActions function
Baby{
move(number){
//some action here...
}
initActions(code){
this.init = Function(code)
this.init()
}
that cause this error
ReferenceError: move is not defined
in baby object initActions
how can i make move available from parent object in function call
someone answered me on irc channel
evalWith(target, code) {
const keys = [], values = [];
for (let o = target; o; o = Object.getPrototypeOf(o))
for (const key of Object.getOwnPropertyNames(o)) {
//console.log(o, key)
try{
let value = target[key];
if (typeof value === "function")
value = value.bind(target);
keys.push(key);
values.push(value);
}catch(e){
//console.log(o,key)
}
}
return Function(keys, code).apply(null, values);
}

Get only values from rows and associations with Sequelize

I am using Sequelize, MySQL and Node to write a web application.
For most of my DB needs, I usually do some verification, then fetch my models (eagerly with associations) and send them back to the client, almost always as-is (at least, up to now).
I wrote a little utility function getValuesFromRows to extract the values from a returned row array:
getValuesFromRows: function(rows, valuesProp) {
// get POD (plain old data) values
valuesProp = valuesProp || 'values';
if (rows instanceof Array) {
var allValues = [];
for (var i = 0; i < rows.length; ++i) {
allValues[i] = rows[i][valuesProp];
}
return allValues;
}
else if (rows) {
// only one object
return rows[valuesProp];
}
return null;
}
// ...
...findAll(...)...complete(function(err, rows) {
var allValues = getValuesFromRows(rows);
sendToClient(errToString(err, user), allValues);
});
However, I am adding more and more complex relations to my DB models. As a result, I get more associations that I have to fetch. Now, I don't only have to call above function to get the values from each row, but also I need more complicated utilities to get the values from all included (eagerly loaded) associations. Is there a way to only get values from Sequelize queries (and not the Sequelize model instance) that also includes all associated values from the instance?
Else, I would have to manually "get all values from each Project and add one item to that values object for the values property of each entry of Project.members" (for example). Note that things get worse fast if you nest associations (e.g. members have tasks and tasks have this and that etc.).
I am guessing that I have to write such utility myself?
I found a simple solution to my problem, by extending my existing POD converting function above with a recursion into all include'd associations of the query. The Solution works with find, findAll, all and possibly other operations with non-trivial results.
Code
/**
* Get POD (plain old data) values from Sequelize results.
*
* #param rows The result object or array from a Sequelize query's `success` or `complete` operation.
* #param associations The `include` parameter of the Sequelize query.
*/
getValuesFromRows: function(rows, associations) {
// get POD (plain old data) values
var values;
if (rows instanceof Array) {
// call this method on every element of the given array of rows
values = [];
for (var i = 0; i < rows.length; ++i) {
// recurse
values[i] = this.getValuesFromRows(rows[i], associations);
}
}
else if (rows) {
// only one row
values = rows.dataValues;
// get values from associated rows
if (values && associations) {
for (var i = 0; i < associations.length; ++i) {
var association = associations[i];
var propName = association.as;
// recurse
values[propName] = this.getValuesFromRows(values[propName], association.include);
};
}
}
return values;
}
Example
var postAssociations = [
// poster association
{
model: User,
as: 'author'
},
// comments association
{
model: Comment,
as: 'comments',
include: [
{
// author association
model: User,
as: 'author'
}
]
}
];
// ...
var query = {
where: ...
include: postAssociations;
};
// query post data from DB
return Post.findAll(query)
// convert Sequelize result to POD
.then(function(posts) {
return getValuesFromRows(posts, postAssociations);
})
// send POD back to client
.then(client.sendPosts);
In the above example, client.sendPosts receives an array. Each entry of the array will have properties author and comments. Each comment in the comments array will also have an author property. The entire array only contains POD (plain old data).

How to get the document using view in couchbase

I have a requirement wherein I have get the document from couchbase.
Following in the Map function that I am using for the same -
function (doc, meta) {
if (meta.type == "json" && doc!=null) {
emit(doc);
}
}
There is no reduce function. Also following is my java code to get the document -
List<URI> hosts = Arrays.asList(
new URI("http://<some DNS with port>/pools")
);
// Name of the Bucket to connect to
String bucket = "Test-Sessions";
// Password of the bucket (empty) string if none
String password = "";
//System.setProperty("viewmode", "development");
// Connect to the Cluster
CouchbaseClient client = new CouchbaseClient(hosts, bucket, password);
String designDoc = "sessions";
String viewName = "by_test";
View view = client.getView(designDoc, viewName);
Query query = new Query();
query.setIncludeDocs(true);
query.setKey(String.valueOf(122));
ViewResponse result = client.query(view, query);
Object object = null;
for(ViewRow row : result) {
if(null != row) {
object = row.getDocument();
}// deal with the document/data
}
System.out.println("Object" + object);
And the data that I have in couchbase is key - "122" and value - "true". But for some reason , I do not get any rows in the ViewResponse. What is going wrong can anyone help?
I don't understand what you are trying to achieve here, you are using a view to get a document by it's key? Key == 122? Why can't you just do client.get(122) ?
If you just need a list of all the keys in your bucket (of which you can use to pull back all documents via include docs) then make your function like so:
function (doc, meta) {
if (meta.type == "json") {
emit();
}
}
The key of the document is always emitted as an ID (viewRow.getId()). You don't need to emit the document, try to emit as little data as possible to keep view sizes small.
If you are needing to manipulate all the documents in your bucket be careful as the size grows, perhaps you'd need to look at pagination to cycle through the results. http://tugdualgrall.blogspot.com.es/
Also once you have the ViewResponse loop over it like so:
for(ViewRow row : result) {
row.getDocument(); // deal with the document/data
}
You don't need to be doing checks for null on the rows.

How can I introspect the signature of a Flex function?

Given a function like
function printAndAdd( s: String, a: int, b: int ) {
// ...
}
Is there any way to enumerate the arguments of the function (their names as well as their types) at runtime? Something like
for ( var arg: ArgumentDescriptor in printAndAdd ) {
// arg.type yields the class object of the argument, i.e. 'String' or 'int'.
// arg.name yields the name of the argument, i.e. 's' or 'a'
}
I have a list of event handlers which have different signatures, and I get the name of the event handler to call as well as an Array of objects. I could just apply() the array to the function, but I'd like to do some error checking first to give better error messages.
You can use describeType() to find the information you seek. However for this to work the function must be public. Private methods will not be introspected by describeType().
Assuming printAndAdd is a method of MyClass, you can do this:
var metadata:XML = describeType(MyClass);
//find all the 'parameter' nodes of any method called 'printAndAdd'
var params:XMLList = metadata..method.(#name == "printAndAdd").parameter;
for each (var param:XML in params) {
var index:int = param.#index;
var type:String = param.#type;
var optional:Boolean = param.#optional == "true";
}
One thing you will not be able to find, is the name of the paramater, but I suppose its index may suffice for your goal.
If you need more powerful reflection than this, take a look at the as3commons reflect library.

Entity Framework Code First - Orphaning solutions?

I have searched around for a good amount of time trying to find a satisfactory solution to the orphan issue common in EF.
One of the simplest forms of orphaning is the clearing of a collection of entities. The relationship between the entities is removed but the child entities still remain in the database.
My requirements: -
The clearing of the collection occurs in the domain and I want to simply be able to call clear and no more.
Any logic to figure out whether the relationship between the parent and child has been broken resulting in the delete needs to be encapsulated within the repository / DbContext.
I don't want to have to 'dirty' the domain with anything additional in order to solve this problem. This includes back references.
I suspect that this can't be solved as I have have spent considerable time looking for solutions but I ask out of hope!
Areas I have looked at are the ChangeTracker and any possible events which I can hook into, similar to AssociationChanged event which has popped up in various places. Something, somewhere in the DbContext must know that this relationship has been broken. How to access it, that is the question?
Thanks.
Can you try the following solution? Mb it fits your needs. The DeleteOrphans extension method must be called between DetectChanges and SaveChanges methods.
public static class DbContextExtensions
{
private static readonly ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>> s_navPropMappings = new ConcurrentDictionary< EntityType, ReadOnlyDictionary< string, NavigationProperty>>();
public static void DeleteOrphans( this DbContext source )
{
var context = ((IObjectContextAdapter)source).ObjectContext;
foreach (var entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Modified))
{
var entityType = entry.EntitySet.ElementType as EntityType;
if (entityType == null)
continue;
var navPropMap = s_navPropMappings.GetOrAdd(entityType, CreateNavigationPropertyMap);
var props = entry.GetModifiedProperties().ToArray();
foreach (var prop in props)
{
NavigationProperty navProp;
if (!navPropMap.TryGetValue(prop, out navProp))
continue;
var related = entry.RelationshipManager.GetRelatedEnd(navProp.RelationshipType.FullName, navProp.ToEndMember.Name);
var enumerator = related.GetEnumerator();
if (enumerator.MoveNext() && enumerator.Current != null)
continue;
entry.Delete();
break;
}
}
}
private static ReadOnlyDictionary<string, NavigationProperty> CreateNavigationPropertyMap( EntityType type )
{
var result = type.NavigationProperties
.Where(v => v.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)
.Where(v => v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One || (v.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.ZeroOrOne && v.FromEndMember.GetEntityType() == v.ToEndMember.GetEntityType()))
.Select(v => new { NavigationProperty = v, DependentProperties = v.GetDependentProperties().Take(2).ToArray() })
.Where(v => v.DependentProperties.Length == 1)
.ToDictionary(v => v.DependentProperties[0].Name, v => v.NavigationProperty);
return new ReadOnlyDictionary<string, NavigationProperty>(result);
}
}