Method Interception, replace return value - ninject

We’re using Ninject.Extensions.Interception (LinFu if it matters) to do a few things and I want to know if its possible to return a value form the method being intercepted.
EG
A Call is made into one of our repository methods
Our Interceptor gets the BeforeInvoke event, we use this to look into the ASP.NET Cache to see if there is any relevant data
- Return the relevant data (this would cause the method to return immediately and NOT execute the body of the method
- Or Allow the method to run as per normal
Extra points if in the AfterInvoke method we take a peek at the data being returned and add it to the cache.
Has anybody done something similar before?

From your question I assume that you derive from SimpleInterceptor. This will not allow to return imediately. Instead you have to implement the Iinterceptor interface. You can decide to call the intercepted method by calling the Proceed method on the invocation or not.

Related

Is it a good practice the attach an event related parameter to an object's model as a variable?

This is about an API handling the validation during saving an object. Which means that the front-end client sends a request to the API to a specific end point, then on the back-end the API creates a new object if the right conditions are meet.
Right now the regular method that we use is that the models has a ruleset for each fields and then the validation is invoked when the save function is invoked, but technically the validation is done right before the object is saved into the database.
Then during today's code review I came across a solution which I wasn't sure if it's a good practice or not. And it was about that the front-end must send a specific parameter to the API every time. This is because other APIs are using our API as well, and we needed to know if the request was sent as and API request or a browser request. If this parameter is present then we want to execute an extra validation function on a specific field.
(1)If I would have to implement it, then I would check the incoming parameter in the service handler or in the controller level, and if I got one, I would invoke the validation right away, and if it fails I would throw an error.
(2)The implementation I saw however adds an extra variable to the model, and sets the model variable when there is an incoming parameter, then validates only when the save function is invoked on the object(which first validates the ruleset defined on the object fields, then saves the object into the database)
So my problem with (2) is that the object now grown bigger with an extra variable that is only related to a specific event. So I would say it's better to implement (1). But (2) also has an advantage, and that is when you create the object on different end point by parsing the parameters, then the validation will work there as well, even if the developer forget to update the code there.
Now this may seems like a silly question because, why would I care about just 1 extra variable, but this is like a bedrock of something good or bad. So if I say this is ok, then from now on the models will start growing with extra variables that are only related to specific events, which I think should be handled on the controller/service handler level. On the other hand the code would be more reliable if it's not the developer who should remember all the 6712537 functionalities and keep them in mind when makes some changes somewhere. Let's say all the devs will get heart attack tomorrow from the excitement of an amazing discovery, and a new developer has to work on the project while he doesn't know about these small details, and then he has to change something on the code that is related to this functionality - so that new feature should be supported by this old one as well.
So my question is if is there any good practice on this, and what do you think what would be the best approach?
So I spent some time on thinking on the solution, and I think the best is to have an array of acceptable trigger variables in the model class. Then when the parameters are passed to the model on the controller level, then the loader function can be modified that it takes the trigger variables from the parameters and save it in the model's associative array variable that stores the trigger variables.
By default this array is empty, and it doesn't matter how much new variables are needed to be created, it will only contain the necessary ones when those are used.
Then of course the loader function needs to be modified in a way that it can filter out the non trigger variables as well as it is done for the regular fields, and there can be even a rule set of validation on the trigger variables if necessary.
So this solves the problem with overgrowing the object with unnecessary variables and the centralized validation part, because now the validation can be always done in the model instead of the controller.
And since the loader function is modified to store the trigger variables in the model's trigger variables array variable, the developer never has to remember that this functionality was created. Which is good, because in the future when he creates a new related function or end point that should handle object creation, he will not miss it to validate it against the old functionality, because the the loader function that he modified in the past like this will handle it for him.
It needs to be noted tho, that since the loader function doesn't differentiate between the parameters, and where to load them other then checking the names of the parameters with the filter functions, these parameter names should be identical from each other, otherwise a buggy functionality can be created accidentally. Like if you forget that a model attribute with the same name was used, then you can accidentally trigger an event that was programmed to be triggered if the trigger variable with the same name is present. However this can be solved by prefixing the trigger variables for example.

Delphi, enhance code of non-virtual methods or events

Although more of a Delphi language question, will use a specific example to try and get the idea across better:
using Delphi's TWebModule for an HTTP server, we can define endpoints as actions, and assign those actions an OnAction event, to execute code when a request is made to this given endpoint.
many, if not most of those actions require authorization: that is, they all start with the same block of code that checks for valid credentials and decides whether to allow the request to execute or not. So I started looking at how one could "group" a set of similar actions into maybe a subclass of the default action class (TWebActionItem) that adds authorization-specific code. One might also want to execute some generic before/after methods.
pseudo-code would look something like this, where TAuthWebActionItem is a subclass of TWebActionItem adding authorization code, and before/after method calls:
function TAuthWebActionItem.OnAction
begin
FBeforeAction // execute some initialization code
if authorized then // auth ok?
inherited // proceed
else
'you are not authorized'
FAfterAction // execute some finalization code
end
we would then create a TAuthWebActionItem, add it to the TWebModule's list of actions, and we're done.
however, the TWebModule and TWebActionItem classes do not offer virtual methods for overriding. Using "reintroduce" instead of "override" would not solve it either, as the TWebModule's actions list items are still of type TWebActionItem: calling the OnAction of a superclass, even if reintroduced, will not execute the subclass' code.
How would one bypass such limitations / constraints in the classes being used, to achieve what's outlined in the pseudo-code above?

Calling Collection.allow() manually to check permissions

In Meteor JS I want to perform a task before adding an object to my collection. So I created my own method, eg: addObject like so:
Meteor.methods({
...
addObject: function(obj) {
/*
// this is what i'm trying to figure out...
if ( !MyColl.allow('insert', Meteor.userId, obj) )
throw Meteor.Error(403, 'Sorry');
*/
MyColl.update({ ... }}, { 'multi': true });
MyColl.insert(obj);
},
...
});
But I noticed that .allow is no longer being called because it's "trusted" code. The thing is the method is on the server but being called from the client (through ObjectiveDDP) so I still need a way to validate that the client has permissions to call addObject - is there any way to manually call .allow() on a collection from my server code? I tried it but getting an internal server error, and not sure what the syntax should be... couldn't find anything in the Meteor docs.
Edit:
I just found out that this works:
var allowedToInsert = MyColl._validators.insert.allow[0];
if (!allowedToInsert)
throw new Meteor.Error(403, 'Invalid permissions.');
But that's probably a no-no calling private methods such as _validators. Does anyone know of a more 'best practices' way?
You can do validation in the addobject method. For example, if you only want logged in users to be able to add an object, you can write:
if (!Meteor.user()) throw new Meteor.Error();
at the beginning of the addobject method.
Personally I never use allow.
On a related note, the collection2 and simple-schema packages can often help a lot with validation.
The validation pattern you are using might not be the best way to do things.
If you assume that methods can be called from the client, you shouldn't 'hack' it into doing something it's not meant to do.
If you are calling a method that changes data in the database you should check within that method that the currently logged in user has permission to do so.
However, are you sure you want to do this? Meteor also has Collection.allow and Collection.deny methods that you can use to define read/write/update/delete permission with. That's the recommended way to handle permissions, so what you are doing is an anti-pattern. However, perhaps in your case it is strictly necessary? If not, you might want to rethink the use case.
Like another response suggests, using something like Collections or SimpleSchema to validate data structure is also a good idea.

If I mock an object and/or stub a method in my spec, will that mock be used even though it's only called indirectly?

I am new to mocking and stubbing, but I think I have a circumstance where their use would be ideal.
In my application, when a user saves a Product, an after_save callback fires that creates Publication instances which cause the product data to be sent to certain 3rd parties via API.
I have a request spec for Product that tests my CRUD operations.
If I stub either the API methods or mock the Publication model, will those mocks/stubs be used in my spec even though they are actually called in the Product after_save callback? I'm confused about this point.
Update
I figured I would just do it like this:
Publication.any_instance.stub(:publist).and_return(true)
And do that at the beginning of my test. That way whatever instance is created would be handled. Is that how it works?
Yes that stub will do what it says and the publist method on any instance of the publication class will always return true.
Instead of putting it "at the top" though do something like.
context 'when there is a publist' do
Publication.any_instance.stub(:publist).and_return(true)
it 'should ...' do
...
end
end
then if required you can do tests without the stub, or tests where publist returns false in other context blocks and be nice and clear in the spec.

Use of deferred execution method in Objective-C

My purpose is as follows: I want to create a deferred calling method. I might need to create a block for this, but I'm not sure. Can you explain me how to create a block for this?
This is the code:
- (IBAction)buyItem:(id)sender {
BOOL purchase = ... /*call purchase method use block*/
}
In this method I make a purchase and after the purchase has completed successfully I want to get result in my variable purchase.
To be more clear:
Step 1: Call the buyItem method.
Step 2: Wait for a response to the purchase (I've omitted the actual methods for the purchase)
Step 3: After the StoreKit object return a response about the purchase, write a value into the variable purchase.
Step 4: After writing the value into purchase, my method buyItem completes execution (go to the } and release).
My question is not about StoreKit specifically (meaning the StoreKit response method - this is an example only). The purchase variable is an example, too. For this variable I will use a data model and it will change after the deferred method executes.
Thanks all!
You do need a block, but maybe a different kind than you're thinking about. You don't need a 'closure', you need a function that will block until it receives the response from the store kit/server.
You can just write a normal buyItem method, but inside you either make a synchronous call to store kit, or if that's not possible, you use threading techniques to achieve what you want. For example, you could wait on a condition variable and then signal it when the store kit call returns.
For both cases, you'll want to perform the 'buyItem' call on a thread other than the UI thread, otherwise your UI will freeze. Given that constraint (if you're even dealing with a UI), I would say this entire approach doesn't make sense. Instead, you'll want to launch the store kit call, set some indicator or spinner or something in your UI, and then when the store kit call returns, unset the spinner or whatever. Make sense?