Ecore decorator - decorator

I have a generated Ecore model - works perfectly fine.
what I now do is, create an instance of the model programmatically and load it:
EARepository repository = EaadapterFactory.eINSTANCE.createEARepository();
repository.setFile(f);
repository.load();
Now I can call the methods like
repository.getName();
works fine!
My Problem: I want to customize the behavior of getName() now!. I would like to set a decorator here, like the genmodel does. E.g. the getName() method should return "no value set" if it has no value set.
Is it possible to customize the getName()'s behavior method here, like setting a decorator ?!
Reason: I want to keep the original behavior of the model. But in one of my use cases, the model should behave a little bit different.
thanks

Generally you should be using the generated item providers for producing the labels you see in the UI. I.e., there is a generated EARepositoryItemProvider with a getText method that you'd specialize for this purpose.

Related

Should default POJO parameter resolution add the parameter to the model?

I just spent some time troubleshooting an aspect of Spring MVC's default handler method parameter resolution and I'd like to ask those closer to the project if this behavior is intended or if it'd be reasonable to open a ticket suggesting a change.
The issue has to do with the default resolution of POJO-style objects in method parameters like this:
#RequestMapping("/endpointwithparams")
public String endpointWithParams(EndpointParams params) {
// Do some stuff
return "viewname";
}
With no annotations or custom argument resolvers, Spring will attempt to bind the EndpointParams object by matching request parameters to its field names. It will even run validators if any are configured. This seems great - it lets me write simple POJO objects to organize related sets of parameters without having to have a custom argument resolver for each one.
The part that throws me off is that after the EndpointParams object is created it will also be automatically added to the model. This is because the actual resolver of this parameter will be a ModelAttributeMethodProcessor with its "annotationNotRequired" flag set to true. I don't want this parameter added to the model - its presence causes some trouble down the line - and it certainly wasn't intuitive to me that I should expect that addition to happen for a parameter that wasn't annotated with #ModelAttribute.
This behavior is also inconsistent with what happens when you have a "simple" request parameter like this:
#RequestMapping("/endpointwithparams")
public String endpointWithParams(String param) {
// Do some stuff
return "viewname";
}
In the above example, the String param will be resolved by the RequestParamMethodArgumentResolver, which will not add anything to the model.
Would it be reasonable to suggest that better default logic for non-annotated POJO parameters would be the same binding and validation that currently occurs, but without the automatic addition to the model? Or is there some context I'm missing that makes the full #ModelAttribute behavior the best default choice?

ASP.Net MVC - ModelState.AddModelError when GET/POST have different models

I have a use case where I used different models for the GET and POST actions in my controller. This works great for my view, because most of the data goes into labels. The model for the GET method contains 10 properties, but the model for the POST method only needs 3.
This GET view renders a form, which only needs 3 of these properties, not all 10. Thus, the model for the POST method accepts a model class which contains only these 3 properties. Therefore, the ASP.Net MVC model binder populates the model class parameter on my POST method with only these 3 necessary properties, and all is well.
Here's the question: When I encounter some business rule violation in the POST method, and want to use ModelState.AddModelError, and re-display the original view, I no longer have the 7 properties that were not POSTed, as they were not part of the form, and are not part of the model class which this method takes as its parameter.
Currently, I'm calling into a builder to return an instance of the model class for the POST method, and have the GET method itself delegating to the same builder. So, in these cases, when there is some business rule violation in the POST method, I return a View("OriginalGetView", originalGetModel). How can I use ModelState.AddModelError in this case, in the POST method, if I want to send custom messages back to the view, using a completely different model class?
It seemed way too lazy to use the same model class for both the GET and POST methods, given that their needs were so different. What is the best practice here? I see a lot of people recommending to use the same model for both methods, and to POST all of the fields back from hidden form fields, but that just seems like a waste of bandwidth in the majority of cases, and it feels ugly to be sending things like "VendorName" back to the server, when I already have "VendorId".
I may be misunderstanding what you are trying to do, but make sure you aren't being penny-wise and pound foolish. I see you may only want to post the identifiers and not necessarily the descriptors. But it sounds like you have to re-display the view after posting...if so you can just access the model properties if you post the same model that is in the get. If you only post the identifiers, you have to spend time re-accessing the database to get the description values(i.e. vendorname as you describe) using the vendor id no? Wouldn't that also be extra processing? Like I said, I could be misunderstanding your post, but for consistency using the same view model for your view to get and post makes the most sense to me.
Hidden Inputs maybe the best solution here still I think, even on 2g you shouldn't create any lag unless unless the values of your Model properties are long strings or something encrypted or xml.
So your .cshtml would have this in it for the 4 properties not currently included in the form:
<form>
#Html.HiddenFor(m => m.Property1)
#Html.HiddenFor(m => m.Property2)
#Html.HiddenFor(m => m.Property3)
#Html.HiddenFor(m => m.Property4)
But you could also get the model state errors from the original posted model and recreate the ModelError state in your response model to get around using hidden inputs.
I just found this guide (not the answer with Green Checkmark but the highest upped Answer: ASP.NET MVC - How to Preserve ModelState Errors Across RedirectToAction?
Note: if you need to copy model properties from Model to another Model (of the same type or different type), in a cleaner way, check out AutoMapper.
Perhaps this could help with what you were trying to achieve - 'Model' level errors - which wouldn't need to attach to a specific field/property - but can be displayed in a Global area.
https://stackoverflow.com/a/53716648/10257093

How to get the form name in class?

I have a form which is used for automatic journal postings.
On that form I have a Ok command button and in closeOk method of the form I call the method from my datasource table.
In the JournalCheckPost class's infoResult() method I want to determine if the method is called from my form. I know that it can be done with caller methods but I don't know how exactly it should be done technically.
It is bad practice to make a method depend on where it is called from.
What you can do is to pass an extra parameter to the LedgerJournalCheckPost and infoResult can then check that. This can be done by introducing a boolean flag and a parm method.
I think, there can be many situations:
You want to pass some parameters from form
You want to manipulate the form (for example refresh datasource after action is complete)
Something other
But in all the cases depending on particular form is not a very good idea.
In first case you can set parameters from code using parm methods, or, better pass parameters using the Args class
In the second you can cast Args.caller to some interface that contain all the methods you want and manipulate the form using that methods (see \Classes\SysFormRun_doRe usages for example)

How to ensure that a method exists in the real object when mocked?

I would like my test to fail if I mock an interface using Mockery and use a shouldReceive with a non-existing method. Looking around didn't help.
For instance :
With an interface :
interface AInterface {
public function foo();
public function bar();
}
And a test case :
function testWhatever{
Mockery::mock('AInterface')->shouldReceive('bar');
$this->assertTrue(true);
}
The test will pass.
Now, refactoring time, bar method is not needed in one place (let's say it's needed on several places) and is suppressed from the interface definition but the test will still pass. I would like it to fail.
Is it possible to do such a thing using mockery (and to be able to do the same thing with a class instead of an interface) ?
Or does a workaround exist with some other tool or a testing methodology ?
Not sur if this can be understood as is, will try to make a clearer description of the issue if needed.
To ensure that Mockery doesn't allow you to mock methods that don't exist, put the following code in your PHPUnit bootstrap file (if you want this behavior for all tests):
\Mockery::getConfiguration()->allowMockingNonExistentMethods(false);
If you just want this behavior for a specific test case, put the code in the setUp() method for that test case.
Check this section of the Mockery manual on Github for more information.
If you want to make sure that the method is called only one time, you can use once().
Suppose that the class AImplementation, implements the interface AInterface, and you wanna tested that the method is called, an example could be:
Mockery::mock('AImplementation')->shouldReceive('bar')->once();
You can also use: zeroOrMoreTimes(), twice() or times(n), checkout the repo at github. Also, I recommend you this tutorial by Jeffrey W

React to change on a static property

I'm re-writing an MXML item renderer in pure AS. A problem I can't seem to get past is how to have each item renderer react to a change on a static property on the item renderer class. In the MXML version, I have the following binding set up on the item renderer:
instanceProperty={callInstanceFunction(ItemRenderer.staticProperty)}
What would be the equivalent way of setting this up in AS (using BindingUtils, I assume)?
UPDATE:
So I thought the following wasn't working, but it appears as if Flex is suppressing errors thrown in the instanceFunction, making it appear as if the binding itself is bad.
BindingUtils.bindSetter(instanceFunction, ItemRenderer, "staticProperty");
However, when instanceFunction is called, already initialized variables on the given instance are all null, which was the cause of the errors referenced above. Any ideas why this is?
You have 2 options that I am aware of:
Option 1
You can dig into the code that the flex compiler builds based on your MXML to see how it handles binding to static properties. There is a compiler directive called -keep-generated-actionscript that will cause generated files to stick around. Sleuthing through these can give you an idea what happens. This option will involve instantiating Binding objects and StaticPropertyWatcher objects.
Option 2
There is staticEventDispatcher object that gets added at build time to classes containing static variables see this post http://thecomcor.blogspot.com/2008/07/adobe-flex-undocumented-buildin.html. According to the post, this object only gets added based on the presence of static variables and not getter functions.
Example of Option 2
Say we have a class named MyClassContainingStaticVariable with a static variable named MyStaticVariable and another variable someobject.somearrayproperty that we want to get updated whenever MyStaticVariable changes.
Class(MyClassContainingStaticVariable).staticEventDispatcher.addEventListener(
PropertyChangeEvent.PROPERTY_CHANGE,
function(event:PropertyChangeEvent):void
{
if(event.property == "MyStaticVariable")
{
someobject.somearrayproperty = event.newValue as Array;
}
});
I think you need to respond to the "PropertyChanged" event.
If you're going to do that, use a singleton instead of static. I don't think it will work on a static. (If you have to do it that way at all, there are probably a couple ways you could reapproach this that would be better).
var instance:ItemRenderer = ItemRenderer.getInstance();
BindingUtils.bindProperty(this, "myProperty", instance, "theirProperty");
After fiddling with this for a while, I have concluded that this currently isn't possible in ActionScript, not even with bindSetter. It seems there are some MXML-only features of data bindings judging by the following excerpt from the Adobe docs (though isn't it all compiled to AS code anyways)?
You cannot include functions or array
elements in property chains in a data
binding expression defined by the
bindProperty() or bindSetter() method.
For more information on property
chains, see Working with bindable
property chains.
Source: http://livedocs.adobe.com/flex/3/html/help.html?content=databinding_7.html
You can create a HostProxy class to stand in for the funciton call. Sort of like a HostFunctionProxy class which extends from proxy, and has a getProperty("functionInvokeStringWithParameters") which will invoke the function remotely from the host, and dispatch a "change" event to trigger the binding in typical [Bindable("change")] Proxy class.
You than let the HostProxy class act as the host, and use the property to remotely trigger the function call. Of course, it'd be cooler to have some TypeHelperUtil to allow converting raw string values to serialized type values at runtime for method parameters (splitted by commas usually).
Example:
eg.
var standInHost:Object = new HostFunctionProxy(someModelClassWithMethod, "theMethodToCall(20,11)");
// With BindingUtils.....
// bind host: standInHost
// bind property: "theMethodToCall(20,11)"
Of course, you nee to create such a utlity to help support such functionality beyond the basic Flex prescription. It seems many of such (more advanced) Flex bindings are usually done at compile time, but now you have to create code to do this at runtime in a completely cross-platform Actionscript manner without relying on the Flex framework.

Resources