Making asynchronous calls in a RIA services method - wcf-ria-services

I have a Silverlight 4 application using RIA services. One of the RIA service methods does something similar to the following:
List<Foo> fooList = this.GetListOfFoo();
AnotherService aService = new AnotherService();
foreach (Foo foo in fooList)
{
aService.SomeMethodCompleted += this.methodCompleted;
aService.SomeMethodAsync(foo);
}
return fooList;
SomeMethodAsync then makes changes to foo, which is a reference type.
this.methodCompleted is called for each Foo, but the updates to the Foo instances are not seen by the Silverlight client. I'm guessing nothing automatically waits for all of the async calls to finish before the RIA service returns to the Silverlight client.
My question is: can I coordinate the completion of the async calls before returning to the Silverlight client? Or am I limited to making only synchronous calls in a RIA service?

The answer is: do it the way you would for any WCF or web service method. That is, an array of WaitHandles that each call to methodCompleted sets, and WaitAll just before returning. Or a CountDownEvent if you're making >64 async calls, like I might need to.
And don't wire up the Completed event handler INSIDE the foreach. Otherwise you'll call your Completed handler (fooList.Count)^2 times, which messes with your CountDownEvent :)

Related

Vert.x run blocking handler before and after other handlers

I'm trying to write a Vert.x Web handler that could be used to hide any processing latencies from an API to prevent figuring out existence of accounts as well as other information from an API. I would like to be able to just write something like:
router
.post("/uri")
.handler(new LatencyNormalizer())
.handler(new UriHandler());
In other words, make it as easy to use as possible and as easy to integrate into existing code bases as possible. Looking at the docs for Router and RoutingContext, I see only the following method as a possible candidate for implementing this:
https://vertx.io/docs/apidocs/io/vertx/ext/web/RoutingContext.html#addHeadersEndHandler-io.vertx.core.Handler-
I could then write code like:
public void handle(RoutingContext ctx) {
long start = System.nanoTime();
ctx.addHeadersEndHandler(v -> {
public void handle(RoutingContext ctx) {
long end = System.nanoTime();
Thread.sleep(...);
});
ctx.next();
}
Of course, this doesn't work, since sleep here blocks the thread. It looks like the handlers in the addHeaderEndHandlers list maintained internally by the RoutingContext are called synchronously, so there is no way to use e.g. vertx.SetTimer() inside the addHeaderEndHandler.
In other words, does Vert.x offer any interface that allows creating a handler which is called asynchronously before writing out to the wire (and with nothing written until the async call finishes)? This is for example how Netty works under the hood, which Vert.x leverages. I know I could implement this LatencyNormalizer as a base class for my other handlers, but it would not be as easy to integrate in existing code in that case.

Benefit of applying Unit-of-Work on Service-layer instead of Controller

When implementing MVC project, I usually add Service Layer to perform the actual work. But actually sometimes 1 Web Request should be done with several AppService methods. Then the location of Unit-of-Work (UoW) may affect the coding handling.
No matter in C# EF/Java Spring, there's Transaction annotation in Service Layer methods, so the transaction is Per-Service based (i.e. UoW on Service layer). Let's take Java version as example here:
#Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
Public class UserAppService{
public UserDTO createUser() {
// Do sth to create a new user
userRepository.save(userBean);
// Convert userBean to userDTO
return userDTO;
}
public xxx DoSth() {
// Break the operation here
throw new Exception("Whatever");
// (never execute actually)
sthRepository.save(someBean);
}
}
Then in Controller:
Public class SomeController : Controller {
Public xxx DoSth(){
UserAppService Service = new UserAppService();
Service.CreateUser(); // DB committed
Service.DoSth(); //Exception thrown
}
}
With this structure, If there's any exception thrown on 2nd service method call, the 1st service method still commit the user to the DB. If I want "all-or-nothing" handling, this structure doesn't work unless I wrap those service method calls into another wrapper service call with single transaction. But it's sort of extra work.
Another version is using transaction on Controller action level instead (i.e. UoW on Controller Action). Let's take C# code as example:
Remarks: AppService in code version 2 here use the DbContext (sth like transaction) defined in controller, and doesn't do any commit inside.
Public class SomeController : Controller {
Public ActionResult DoSth(){
using (var DB = new DbContext()){
Var UserAppService = new UserAppService(DB);
var userEntity = userAppService.GetUser(userId);
UserAppService.DoSth(userEntity);
Var AnotherAppService = new AnotherAppService(DB);
AnotherAppService.DoSthElse(userEntity);
// Throw exception here
throw new Exception("Whatever");
DB.Save(); // commit
}
}
}
In this example, there will be no partial commit to the DB.
Is applying UoW on service-layer really better?
Is applying UoW on service-layer really better?
IMO No. And you've just figured out why. If the service methods are discreet and re-usable, they are also not suitable for being atomic transactions.
In .NET the controller should control the transaction lifecycle, and enlist service methods in the transaction.
Note that this also implies that the service methods should be local method calls, not remote or web service calls.
It is better because your following the main principle of Object Oriented Programming seperation of concerns.What if you made another controller and wanted to do more database processing using the same object? You dont want to instantiate the controller in which your doing something completely different.By the way check out the facade service pattern http://soapatterns.org/design_patterns/service_facade it may help you understand why its so sexy. .Hi the image above shows the pattern, basically you wrap your database access objects with transactional at the service layer so a customerService object can wrap 1,2...inf transactions and either all fail or succeed.

WCF with IOperationInvoker using Entity and Ninject

I have a WCF Service from which I need to log the calls to its methods. For this, I used this solution to be able to track the calls and call my internal audit service, which uses Entity 5.1 and injects the services/repositories/DbContext using Ninject.
My Invoke method looks like this:
public object Invoke(object instance, object[] inputs, out object[] outputs)
{
var methodParams = (instance).GetType().GetMethod(_operationName).GetParameters();
var parameters = new Dictionary<string, object>();
for (var index = 0; index < inputs.Length; index++)
parameters.Add(methodParams[index].Name, inputs[index]);
_auditService.TrackFilterParametersValues(_operation.Parent.Type.FullName, _operationName, _operation.Action, parameters);
return _baseInvoker.Invoke(instance, inputs, out outputs);
}
In my Ninject module I have the internal stuff registered like this:
Bind<IAuditService>().To<AuditeService>().InRequestScope();
Bind(typeof(IRepository<>)).To(typeof(Repository<>)).InRequestScope();
Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
Bind<DbContext>().To<MyEntities>().InRequestScope();
Problem comes up when, inside the Repository, I call the dbContext to add the new Audit object like this:
_dbContext.Set<T>().Add(entity);
It errors out claiming that the DbContext has been disposed.
What would be the correct way of registering the DbContext on a WCF Service so it gets registered for an IOperationInvoker??
I have to mention that I have all this declaration the same for the main site I'm feeding up with this backend in MVC4 and it works perfectly (no WCF there). So I'm pretty sure something is needed to be corrected for the WCF lifetime cycle, but not so sure about what.
I found the reason of why this was behaving so nasty: in the chain formed by the IOperationInvoker, IOperationBehavior and IServiceBehavior, I was injecting the AuditService by the constructor of the first 2 of them, but in the latest (IServiceBehavior), since I was decorating the WCF class with it and couldn't overload the constructor, I was using the DependencyResolver to obtain the AuditService with a property like this:
public IAuditService AuditService
{
get { return DependencyResolver.Current.GetService<IAuditService>();
}
Then, when I started to debug, I noticed that the constructors were called when the WCF Test Client was querying the WCF for the WSDL data, but the Invoke method was never called because no web method was being invoked. So the AuditService instance (and DbContext) was all fine during the calls of the constructors, but by the time of invoking a web method and calling the Invoke method of the IOperationInvoker, the DbContext was already disposed long time ago.
My workaround for this was to delete all the references to the AuditService from all constructors and move the property with the DependencyResolver from the ServiceBehavior to the IOperationInvoker implementation. Once I did this, the AuditService is called right when it's needed, never before, and its DbContext is never disposed.
If MyEntities inherits from DbContext, then this should work:
Bind(typeof(DbContext)).To(typeof(MyEntities)).InRequestScope();

Function Return void How to Run with Open RIA Domain Service

I have few Functions & Procedures to Run from Silverlight project. I have mapped data in EF6. Now I want to Run these function Using OpenRIA Service. I tried giving annotation like Query, Update, Insert, Delete. One or other function does some of these operations. Few return nothing & Few return data.
I wrote a method to call 1 Function from RIA Domain Service
public void BuildRoute4Rdinv(decimal? hpmsyear, string errorout)
{
this.ObjectContext.BuildRoute4Rdinv(year, ref errorout);
}
What Annotation I should provide in above case. this function doesnt return anything & Have no complex type associated with. [Query] requires Return IEnumarable so i cant provide that.
I think the one you are after is "[Invoke]"
Annotate your function with [Invoke] then a related method will be generated on your client side.

Entity Framework Generic Repository Context

I am building an ASP.NET 4.0 MVC 2 app with a generic repository based on this blog post.
I'm not sure how to deal with the lifetime of ObjectContext -- here is a typical method from my repository class:
public T GetSingle<T>(Func<T, bool> predicate) where T : class
{
using (MyDbEntities dbEntities = new MyDbEntities())
{
return dbEntities.CreateObjectSet<T>().Single(predicate);
}
}
MyDbEntities is the ObjectContext generated by Entity Framework 4.
Is it ok to call .CreateObjectSet() and create/dispose MyDbEntities per every HTTP request? If not, how can I preserve this object?
If another method returns an IEnumerable<MyObject> using similar code, will this cause undefined behavior if I try to perform CRUD operations outside the scope of that method?
Yes, it is ok to create a new object context on each request (and in turn a call to CreateObjectSet). In fact, it's preferred. And like any object that implements IDisposable, you should be a good citizen and dispose it (which you're code above is doing). Some people use IoC to control the lifetime of their object context scoped to the http request but either way, it's short lived.
For the second part of your question, I think you're asking if another method performs a CRUD operation with a different instance of the data context (let me know if I'm misinterpreting). If that's the case, you'll need to attach it to the new data context that will perform the actual database update. This is a fine thing to do. Also, acceptable would be the use the Unit of Work pattern as well.