How to find all resourcepools in Anylogic - anylogic

Is there a way to find all resourcepools in the main agent? E.g. I have created different resourcepools like operator, equipment, storage, etc. And i want to store all of them in a collection. But instead of manually adding them to the collection, can i search through the entire main agent for all the resourcepools and directly add them to the collection using Java?

Sure. Loop through objects and check if they are resource pools. If you are on Main, you can call this code, it checks all objects on Main (or where ever you call it from):
for (Object currentObject : getObjects(){
if (currentObject instanceof ResourcePool) {
// add here
}
}

Related

Post-Initialization in extbase domain model

In one of my extbase models, I want to initialize some properties derived from the properties that are saved in the database. The computation of these virtual properties is time consuming, so I'd like to cache them. Thus my program flow should look somehow like this:
Load the domain object as usual from the database
Check if the virtual property is available in cache. If so, fetch it from there, otherwise compute and cache it.
I first thought the method "initializeObject" is what I need, but it is not: It is called before any property is initialized from the database. So I came up with two other ways:
I can call an initialization-method manually from the repository after fetching the object, but that seems weird and would break if someone adds another find* method to the general repository.
Another idea is to add a boolean "virtualPropertiesInitialized" to the model, query it whenever one of the virtual properties is accessed and initialize the virtual properties if needed. Also seems weird, but would not break if someone adds another "find"-method to the generic repository.
My question is:
Is there a default/best-practice how to do what I want to do?
If reading the final value from disk or database is less computationally intensive, then store the value using the TYPO3 caching framework or by your own caching method of a static class and restore it in the getter of the virtual property. Doing it in the getter method public mixed getYourPropery() will give you the feature that the value is only get from the cache when you call it.
On the second call, just return the value you stored previously:
private $myValue = NULL;
public function getMyValue() {
if($this->myValue != NULL) return $this->myValue;
$this->myValue = "test";
return $this->myValue;
}

GWT MVP updating Activity state on Place change

What is the best practise to update Activity state on Place change? Imagine you have an activity with view that displays list of categories and list of items in the category. If different category is selected then app goes to new place with category ID. I want then to only refresh items and not to create new activity that also re-reads category list.
My current approach is like this:
public class AppActivityMapper implements ActivityMapper {
private ItemListActivity itemListActivity;
...
public Activity getActivity(final Place place) {
final Activity activity;
if (place instanceof ItemListPlace) {
if (itemListActivity == null) {
itemListActivity = new ItemListActivity((ItemListPlace) place, clientFactory);
} else {
itemListActivity.refresh((ItemListPlace) place);
}
activity = itemListActivity;
} else {
itemListActivity = null;
}
...
return activity;
}
...
Alternatives are:
listen to PlaceChangeEvents from within the activity (you can then use a FilteredActivityMapper and CachingActivityMapper for the caching of the activity in your ActivityMapper, so that it's reduced to only create a new activity when asked). †
have some component listen to PlaceChangeEvents and translate them to business-oriented events, the activity then listens to those events rather than PlaceChangeEvents, otherwise the same as above.
decouple the activity from the "screen", make the "screen" a singleton with a reset() method and call that method from the activity's start (possibly passing the category ID as an argument in this case). The "screen" being a singleton could then make sure to load the categories list only once.
in your case, you could also simply put the categories list in a shared cache, so that you don't have to reuse your activity by can create a new one, the categories list will be retrieved once and put in the cache, subsequent activity instances will just use what's in the cache. This is similar to the above, but simpler, and the cache could be used by other parts of the application.
I'd personally rather go with your approach though (with a small exception, see below), as it's the simplest/easiest. Decoupling the activity from the "screen" is also an option; the GWT Team started exploring this approach in the Expenses sample (decoupling the activity responsibility from the presenter responsibility with using MVP) without ever finishing it unfortunately.
Other than that, I don't think any best practice has really emerged for now.
†. I don't like coupling my activities with the places they're used with (I don't quite like the coupling for the goTo calls either, but haven't yet found a clean and simple alternative), so I'd rather not go with this option; and similarly, I'd not pass the place to the activity constructor and refresh method like you did, but rather extract the information out of the place and pass it to the activity (e.g. in your case, only give the category ID to the activity, not the ItemListPlace instance; I would then simply call setCategory in all cases, and not even pass the category ID to the constructor).
In my opinion,
The role of the ActivityMapper is to give you back an Activity from a Place.
The role of the ActivityManager is to start the Activity given back from the ActivityMapper and to stop the current one if different. In your case you would like to "update/refresh" the current Activity.
So I would modify the ActivityMapper so as it will allways give me back the same instance of Activity for a given type of Place. A good way to do so could be to use GIN and use the singleton scope ...in(Singleton.class) to inject your Activity.
If you do that, when changing the url, if the place stays the same (meaning your url has the same word after # and before :) so that the Type of your place stays the same, the ActivityMapper will give you back the same instance of Activity so the ActivityManager will do nothing on the Activity. Check l.126 of ActivityManager
if (currentActivity.equals(nextActivity)) {
return;
}
For me you have 2 options there. The first one, as Thomas said , is to listen to PlaceChangeEvent in your Activity. The new Place you will receive can have new parameters inside based on the new url given and you can "update/refresh" your Activity.
The second one, that I find more in line with the Activity/Place pattern is to modify the ActivityManager so that it calls an update(Place) method on the Activity when the Activity given back by the ActivityMapper is the same that the current Activity.
I haven't tried any of these solutions yet but I will soon ... I might be able to update that post at that time.
You can find more information in this article I wrote on my blog on that topic
Here is a little schema I made to help me understand the pattern, hope it will help :
I would not do any logic in my ActiviyMapper except returning an activity, by creating a new one or giving a previous one (or null). According to me, the mapper doesn't have to know about refresh() or what activities do.
If that, then the logic of 'refresh()' would be given to the activy through the place which holds a token. That token should be holding the information about either what is the state of the request (a new page, reload, an id, etc).
In the activity, first, it asks for the View, the one related to this activity (tip : a singleton given by a 'ClientFactory' is good practice), then it creates a presenter for that view, and bind them together.
Lastly, the activity will use the token from the place to provide any information about state to the presenter. And then, it adds the view in the page.
It's good to know by default, with places and activies, going to the same place doesn't do anything (no reload). But you can take care of it with token and activity-mapper easily.
Hope you'll find an adapted solution for you case. Goodluck.

How can I add an existing instance to a MEF catalog?

I have an object instance, and I want to end up with a MEF catalog that contains that object instance, exported as a specific interface type. How can I do this?
TypeCatalog doesn't seem workable here, because (a) it creates a new instance instead of using an existing one, and (b) it requires the type to have an [Export] attribute. In my case, the instance comes from MEF's metadata system, so MEF creates the underlying type and I can't add attributes to it.
As far as I can tell, the usual advice is, if you've got an existing instance, you should add it to the container (e.g. via CompositionBatch), not to the catalog. But when I add this instance, I'm also adding an entire AssemblyCatalog worth of types, all in the same operation. I'll also want to be able to remove all of these types later. It makes more sense to me to bundle everything into an AggregateCatalog. That way, I can add both the assembly and the instance in one atomic operation, and I can remove them all again the same way.
For example:
// Bootstrapper code to initialize MEF:
public void Configure() {
_selectedGameCatalog = new AggregateCatalog();
var globalCatalog = new AggregateCatalog(_selectedGameCatalog);
_container = new CompositionContainer(globalCatalog);
// ... more MEF initialization ...
}
// Sometime later, I want to add more stuff to the MEF ecosystem:
public void SelectGame(Lazy<Game, IGameMetadata> entry) {
var newCatalog = new AggregateCatalog();
// Make the assembly available to import:
newCatalog.Catalogs.Add(new AssemblyCatalog(entry.Value.GetType().Assembly));
// I also want the metadata to be available to import:
IGameMetadata metadata = entry.Metadata;
newCatalog.Catalogs.Add(MakeCatalogFromInstance<IGameMetadata>(metadata));
// Replace whatever game was selected before:
_selectedGameCatalog.Catalogs.Clear();
_selectedGameCatalog.Catalogs.Add(newCatalog);
}
The part I don't know how to do is "MakeCatalogFromInstance". How can I create a catalog that contains an existing instance (registered as a specific type)?
Or, alternatively, if I'm going about this all wrong, is there a better way to plug an entire catalog and an existing instance all into MEF at the same time, with the ability to unplug them all again later and replace them with something else?
I think it's probably best to add the types to the catalog and then add the instance to the container.
Catalogs contain part definitions. Part definitions are used to create parts. (The types for this are ComposablePartDefinition and ComposablePart.) So you could theoretically write your own catalog and a part definition that always returned a part corresponding to the instance when CreatePart was called. But catalogs weren't really designed to be used this way.
For prosperity...
MEF devivides the chores of what type info is to be used (catalog) from the actual running object instances (container). To me it is a logical descicion, especially when you setup a more complex MEF environment in your application.
If you want the ability to 'change' containers on the fly, I would suggest you try to use hierarchical containers. The root catalog/container is filled with static types and any of the child containers can be filled with each specific set of meta types you need for your game.
Hope it helps,
Marc

A question about the Repository pattern and MVVM

I have a repository named MemberRepository which is used by the MemberListViewModel and the MemberEditViewModel. In the repository I have my GetMember(), CreateMember, SaveMember, Rollback(), and DeleteMember().
Throughout my app I have numerous lookup tables that populate comboboxes. Example Status, Trade Code, Agent, User etc. Where do I place the GetUsers, GetStatuses(), GetTradeCodes() methods? In the appropriate repositories in which they are used?
For example, the member view model needs a list of statuses, trade codes, classes, etc. So I would put the gets for these in the MemberRepository?
Bill
Ok, so your MemberListViewModel is for a listing page and your MemberEditViewModel is an editing page.
What I would do, in my model, is expose the following classes:
ListMembersTask
EditMemberTask
You inject these with all the repositories each one would need, and they expose the properties and methods needed by some abstract thing that's performing each task. For instance, ListMembersTask might have a method called CreateMember() that returns a new EditMemberTask initialized with an empty Member object.
Your ViewModel then gets injected with the appropriate Task (so MemberListViewModel gets injected with ListMembersTask, etc.). Your MemberListViewModel would have a RelayCommand that called CreateMember() and took the returned EditMemberTask, injected it into a MemberEditViewModel and passed the new MemberEditViewModel to the presenter.
If you follow that approach, then the Repositories are only responsible for persistence. A task wraps up the state of the business logic during a session, and a view-model just makes a task bindable.
The next step I've been working on is to dispense with the Task-specific view-models, and I now hand a raw Task to the Presenter, and it inspects the object and builds a view-model hierarchy for the task out of elementary view-model elements (like EditTextViewModel, ChooseOneViewModel, DockingLayoutViewModel, etc.).

Loading workflow activity dynamically from XOML

I am trying to implement an activity similar to InvokeWorkflow, which could dynamically load a XOML file, instantiate an activity tree from it, and use it as its only child.
This would be similar to InvokeWorkflow except that the activities which are dynamically loaded are inlined into the main workflow (which is better from a monitoring perspective).
I looked at XamlReader as a potential way of doing this, but apparently it is not suitable for loading workflows (only UI stuff).
Thanks,
Julien
Achieving your goal here is likely to be quite tricky however lets start with the easy bit:-
You can reconstruct a workflow from XOML using the WorkflowMarkupSerializer found in the System.Workflow.ComponentModel.Serialization namespace.
var serializer = new WorkflowMarkupSerializer();
object root = serializer.Deserialize(myXmlReader);
Similarly you could reconstruct a "snippet" of activities held in something that inherits from CompositeActivity using the CompostiteActivityMarkupSerializer.
However, to integrate the new root activity into the currently running workflow requires more work. You need to use an instance of the WorkflowChanges class to make the new activity by modifing the Workflow definition used by the current instance.
Now the documentation is some what sketchy and even a little evasive on this subject. Two important points can be gleaned though:-
Ultimately a call to ApplyWorkflowChanges is needed and this member has protected accessibility.
The documentation indicates that this needs to occur on the root activity of a workflow.
Hence we can deduce that we will need a custom root activity to at least assist in this requirement.
There are probably more ways that this could be structured but lets assume we have a SequenceActivity in which we have a custom "InvokeWorkflow" activity performing the workflow modification and we intend to place the resulting new activity at the end this containing sequence.
First we'll need an interface definition which we can implement on the custom root activity:-
internal interface IModifiableWorkflow
{
void ApplyWorkflowChanges(WorkflowChanges workflowChanges);
}
In our custom root activity we would implement this interface explicitly:-
public class CustomSequentialActivity : SequentialWorkflowActivity, IModifiableWorkflow
{
void IModifiableWorkflow.ApplyWorkflowChanges(WorkflowChanges workflowChanges)
{
base.ApplyWorkflowChanges(workflowChanges);
}
}
In the Execute method of the custom "InvokeWorkflow" activity:-
// Get root activity
var root = this.Parent;
while (root.Parent != null) { root = root.Parent; }
// Create an instance of WorkflowChanges based on the root activity
var changes = new WorkflowChanges(root);
//Find the parent sequence activity in the transient workflow definition
var target = changes.TransientWorkflow.GetActivityByName(this.Parent.Name);
Activity newActivity = YourCodeToLoadActivityDetailsFromXoml();
target.Activities.Add(newActivity);
//Apply the new changes
((IModifiableWorkflow)root).ApplyWorkflowChanges(changes);
Note I haven't actually tested any of this, its cobbled together from crumbs of info buried in the documentation.
Thanks so much Anthony.
I have to say that your dynamic workflow modification is cool, but it was a little scary. I ended up composing workflows using a modification of Jon Flander's CallWorkflowActivity.
Some tricks I learned with XOML-only workflows loaded at runtime (using WF 3.5):
remove x:Class attribute inside the XOML
delete the code-behind file
for the VS designer to work, those XOML files need to be separated in their own projects (no code, such as base activities or common types, in the project where the XOML is located)
mark the XOML as Content in VS and Copy Always so it is placed with your binaries
even so, VS 2008 usually needs a full Rebuild in order to properly copy newly modified XOML files...
you may need to set breakpoints manually, as explained here