invoking 2 targets with Castle.DynamicProxy - castle-dynamicproxy

Say I have an interface IInterface.
Say I have 2 implementations of the same IInterface (foo & bar).
Is it possible to invoke the same method on both targets?

It depends how you approach it,
Generally its not possible (which return value should be returned?), but nothing stops you from having another target wrapped in an interceptor, and having it invoked by the interceptor.

I came up with this, but it uses reflection so it's not as good as "native" support for Y-adapter type of proxy...
public void Intercept(IInvocation invocation)
{
invocation.Proceed();
ThreadPool.QueueUserWorkItem(new WaitCallback(
(object o) =>
{
invocation.Method.Invoke(newTarget, invocation.Arguments);
}
)
);
}
Using the QueueUserWorkItem guarantees that the thread invoking the method is not going to suffer much in terms of performance...
Any better solution is more than welcome!

Related

Is fireUserEventTriggered correct way to "glue" non-netty callback-providing services with netty pipline?

Good day!
Wondering if using fireUserEventTriggered/userEventTriggered is netty way to collaborate with callback-oriented external services while processing message in channel handlers?
I mean, if there is some "alien" service with nonblocking(callback mechanic) methods, is this is right way to call ChannelHandlerContext#fireUserEventTriggered(passing some params from callback closure) and then handle it within overloaded ChannelInboundHandler#userEventTriggered for continue communication within original channel where it all started.
Example for illustration
#Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
externalServiceWithAsyncApi.doAndRegisterCallback(
//some call that will finish later and trigger callback handler
(callbackParam)->
ctx.fireUserEventTriggered(
new ExternalServiceCallbackEvent(callbackParam)
)
);
}
#Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
//seems its for us to handle
if (evt instanceof ExternalServiceCallbackEvent) {
//some processing and answer in the original?
ctx.channel()
.writeAndFlush(...)
.addListener(...);
// let other handlers process
} else {
super.userEventTriggered(ctx, evt);
}
}
Seems example with HeartbeatHandler in "Netty in Action" (in Listing 11.7) is relevant, but this part is a bit ahead from my current point of reading, so decided to ask for a help.
There is very similar question but something did not work for author and no answer Netty, writing to channel from non-Netty thread
UPD
The correct way seems to call NOT
ctx.fireUserEventTriggered(...)
but
ctx.channel().pipeline().fireUserEventTriggered(...)
It's definitely something you could used for that. That said you can also just do the write directly from your callback.

In ASP.NET, why does DbSet.LastAsync() not exist?

I've make some codes implementing some web API.
This API method returns last record of Foo Table.
public class FooController : ApiController
{
private FooContext db = new FooContext();
// GET: api/Foo
[ResponseType(typeof(Foo))]
public async Task<IHttpActionResult> GetLastFoo()
{
Foo foo = await db.Foo.Last();
if (foo == null)
{
return NotFound();
}
return Ok(foo);
}
}
I want make this API asynchronous, but there is no LastAsync() method.
Why and how can I solve it?
Thanks in advance.
You should not use Task.Run in ASP.NET:
Async and await on ASP.NET are all about I/O. They really excel at
reading and writing files, database records, and REST APIs. However,
they’re not good for CPU-bound tasks. You can kick off some background
work by awaiting Task.Run, but there’s no point in doing so. In fact,
that will actually hurt your scalability by interfering with the
ASP.NET thread pool heuristics. If you have CPU-bound work to do on
ASP.NET, your best bet is to just execute it directly on the request
thread. As a general rule, don’t queue work to the thread pool on
ASP.NET.
From Async Programming : Introduction to Async/Await on ASP.NET
Still it does not mean you can't use async and await in ASP.NET for I/O (and that's what you want) just use real async methods and not a fake async wrappers over synchronous methods (that will just push the work into other ThreadPool thread and you will not gain any performance benfit from it).
Since you don't have LastAsync method in EF I suggest you to use OrderBy to order your collection as you want and to use FirstAsync method (or FirstAsync overload that supports lambda predicate) instead of using Last method, FirstAsync is a true async I/O method that is supported in EF.
More info about when it's appropriate to use Task.Run can be found in Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation article in Stephen Cleary's blog.
Your question why there is no LastAsync method in the first place should be directed to the team at Microsoft that desiged EF api, but my guess is that they didn't bother implementing it since it is so easy to achieve the same functionally with FirstAsync method as I suggested.
A working version of that code would look like this:
public class FooController : ApiController
{
private FooContext db = new FooContext();
// GET: api/Foo
[ResponseType(typeof(Foo))]
public async Task<IHttpActionResult> GetLastFoo()
{
Foo foo = await db.Foo.OrderByDesc(x=> x.Timestamp).FirstOrDefaultAsync();
if (foo == null)
{
return NotFound();
}
return Ok(foo);
}
}
Last etc don't work against an EF IQueryable because SQL doesn't have an equivalent command
about how to solve it
you can use
await Task.Run(()=>db.Foo.Last());

Solution for asynchronous notification upon future completion in GridGain needed

We are evaluating Grid Gain 6.5.5 at the moment as a potential solution for distribution of compute jobs over a grid.
The problem we are facing at the moment is a lack of a suitable asynchronous notification mechanism that will notify the sender asynchronously upon job completion (or future completion).
The prototype architecture is relatively simple and the core issue is presented in the pseudo code below (the full code cannot be published due to an NDA). *** Important - the code represents only the "problem", the possible solution in question is described in the text at the bottom together with the question.
//will be used as an entry point to the grid for each client that will submit jobs to the grid
public class GridClient{
//client node for submission that will be reused
private static Grid gNode = GridGain.start("config xml file goes here");
//provides the functionality of submitting multiple jobs to the grid for calculation
public int sendJobs2Grid(GridJob[] jobs){
Collection<GridCallable<GridJobOutput>> calls = new ArrayList<>();
for (final GridJob job : jobs) {
calls.add(new GridCallable<GridJobOutput>() {
#Override public GridJobOutput call() throws Exception {
GridJobOutput result = job.process();
return result;
}
});
}
GridFuture<Collection<GridJobOutput>> fut = this.gNode.compute().call(calls);
fut.listenAsync(new GridInClosure<GridFuture<Collection<GridJobOutput>>>(){
#Override public void apply(GridFuture<Collection<GridJobOutput>> jobsOutputCollection) {
Collection<GridJobOutput> jobsOutput;
try {
jobsOutput = jobsOutputCollection.get();
for(GridJobOutput currResult: jobsOutput){
//do something with the current job output BUT CANNOT call jobFinished(GridJobOutput out) method
//of sendJobs2Grid class here
}
} catch (GridException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
return calls.size();
}
//This function should be invoked asynchronously when the GridFuture is
//will invoke some processing/aggregation of the result for each submitted job
public void jobFinished(GridJobOutput out) {}
}
}
//represents a job type that is to be submitted to the grid
public class GridJob{
public GridJobOutput process(){}
}
Description:
The idea is that a GridClient instance will be used to in order to submit a list/array of jobs to the grid, notify the sender how many jobs were submitted and when the jobs are finished (asynchronously) is will perform some processing of the results. For the results processing part the "GridClient.jobFinished(GridJobOutput out)" method should be invoked.
Now getting to question at hand, we are aware of the GridInClosure interface that can be used with "GridFuture.listenAsync(GridInClosure> lsnr)"
in order to register a future listener.
The problem (if my understanding is correct) is that it is a good and pretty straightforward solution in case the result of the future is to be "processed" by code that is within the scope of the given GridInClosure. In our case we need to use the "GridClient.jobFinished(GridJobOutput out)" which is out of the scope.
Due to the fact that GridInClosure has a single argument R and it has to be of the same type as of GridFuture result it seems impossible to use this approach in a straightforward manner.
If I got it right till now then in order to use "GridFuture.listenAsync(..)" aproach the following has to be done:
GridClient will have to implement an interface granting access to the "jobFinished(..)" method let's name it GridJobFinishedListener.
GridJob will have to be "wrapped" in new class in order to have an additional property of GridJobFinishedListener type.
GridJobOutput will have to be "wrapped" in new class in order to have an addtional property of GridJobFinishedListener type.
When the GridJob will be done in addition to the "standard" result GridJobOutput will contain the corresponding GridJobFinishedListener reference.
Given the above modifications now GridInClosure can be used now and in the apply(GridJobOutput) method it will be possible to call the GridClient.jobFinished(GridJobOutput out) method through the GridJobFinishedListener interface.
So if till now I got it all right it seems a bit clumsy work around so I hope I have missed something and there is a much better way to handle this relatively simple case of asynchronous call back.
Looking forward to any helpful feedback, thanks a lot in advance.
Your code looks correct and I don't see any problems in calling jobFinished method from the future listener closure. You declared it as an anonymous class which always has a reference to the external class (GridClient in your case), therefore you have access to all variables and methods of GridClient instance.

How can i get an immediate response from a long running process in j2ee?

I can't seem to find a solid answer anywhere. I THINK i found one with respect to JMS but it was confusing.
It really depends what stack of j2EE are you using? Is it just web, ejb layer or both?. If we are talking about the web then you can use asynchronous servlet introduced in the newest Java EE specification, if you are using plain EJB's then the natural choice would be Messege driven beans (mentioned JMS). You can of course design a custom solution where for example you send some data to process and then the j2ee application itself calls your application (with http request for example) to notify that its done running the job. Possibilities are endless and if one is better than other always depends on the specific scenario.
If I understand correctly what you are talking about is the ability to start a task (that will take some time) then respond to the user while that task is still doing it's stuff. Depending on your requirements it is really quite simple and you can use a plain old Java Thread to perform the operation.
public class DoSillyCounting extends Thread {
private volatile int counter;
public int getCounter() { return counter; }
public run() {
while (counter < 10) {
counter ++;
try { Thread.sleep(1000); }
catch (InterruptedException ie) { }
}
}
}
In your setup page you might do this: (session is an HttpSession)
DoSillyCounting doSillyCounting = new DoSillyCounting();
doSillyCounting.start();
session.putValue("tenSecondsCounter", doSillyCounting);
/* Here you can respond to the user while the Thread is executing */
And in your status page you might do this:
DoSillyCounting doSillyCounting =
(DoSillyCounting)session.getValue("tenSecondsCounter");
out.print(Integer.toString(doSillyCounting.getCounter());
if (doSillyCounting.isAlive()) {
out.print("Still Working on it");
} else {
out.print("Yippee, I finished");
}
Of course, this is a rather useless example and this model is not a good idea when you may have a large number of requests to satisfy, it would then be worth looking at a ThreadPool implementation or using something like JMS.

Dispatching to the UI thread still required when using MVVM Light?

I'm hoping this isn't too dumb a question: I just started using MVVM light (love it so far! ). In the "before time" (ie before the use of MVVML), I had to ui dispatch any code that would hit a property setter that had an INotifyPropertyChanged event raised in it.
I had (incorrectly? ) thought that requirement would disappear when using MVVMlight.
I still have to use it, correct? My experiments tell me a resounding yes.
So, heres the really stupid part - since there is a requirement to initialize the MVVML dispatcherhelper class somewhere, where I assume it saves the UI thread, why not have the RaisePropertyChanged call do the Dispatch automagically? It seems like a common thing to do?
Not a criticism per se, more of a "how come it doesn't work this way" :-)
Edit (copied from from a comment by author)
FWIW, I did this:
public class QViewModelBase : ViewModelBase {
protected override void RaisePropertyChanged(string propertyName) {
DispatcherHelper.CheckBeginInvokeOnUI( () => base.RaisePropertyChanged(propertyName));
}
protected override void RaisePropertyChanged<T>(string propertyName, T oldValue, T newValue, bool broadcast) {
DispatcherHelper.CheckBeginInvokeOnUI( () => base.RaisePropertyChanged<T>(propertyName, oldValue, newValue, broadcast));
}
}
Please refer to my answer here: Thread safe, Silverlight
I highly recommend exactly what you are suggesting.
IMO you don't need to dispatch at all!
Only operations on ObservableCollection need dispatching.
Reference answer: Accessing ViewModel properties from separate thread

Resources