WCF service asynch / synch - mysql

I am new to WCF, I am using it to access MySql in silverlight application.
I have something simple like this:
[OperationContract]
public List GetPolitics()
{
return _registrationData.GetPolitics();
}
where RegistrationData is a .NET assembly that communicates with the MySql using MySqlConnection.
My question is, the WCF creates Async operations by default, is there a way to have a synchronous operation that blocks on the call while the DB is being fetched ? if so how ?

It's weird that according to your code, you have already used the synchronized operation. If you want to provide async operation, you need to provide a pair of method: BeginXXX, EndXXX. Please read this: Synchronous and Asynchronous Operations
And what do you mean by blocking the call? do you want to block the thread on server side?

Related

How to use Hystrix with Spring WebFlux WebClients?

I'm using Spring WebFlux with functional endpoints to create an API. To provide the results I want, I need to consume an external RESTful API, and to do that in a async way I'm using a WebClient implementation. It works well and goes like this:
public WeatherWebClient() {
this.weatherWebClient = WebClient.create("http://api.openweathermap.org/data/2.5/weather");
}
public Mono<WeatherApiResponse> getWeatherByCityName(String cityName) {
return weatherWebClient
.get()
.uri(uriBuilder -> uriBuilder
.queryParam("q", cityName)
.queryParam("units", "metric")
.queryParam("appid", API_KEY)
.build())
.accept(APPLICATION_JSON)
.retrieve()
.bodyToMono(WeatherApiResponse.class);
}
As this performs network access, it's a good use case for NetFlix OSS Hystrix. I've tried using spring-cloud-starter-netflix-hystrix, adding #HystrixCommand to the method above, but there's no way to make it trip the circuit, even if I set a bad URL (404) or wrong API_KEY (401).
I thought this could be a problem of compatibility with the WebFlux itself, but setting property #HystrixProperty(name="circuitBreaker.forceOpen", value="true") indeed forces the fallback method to run.
Am I missing something? Is this approach incompatible with Spring WebClients?
Thanks!
#HystrixCommand won't really work, because Hystrix doesn't threat Mono/Flux any different from Java primitives.
Hystrix doesn't monitor content of Mono, but only the result of call public Mono<WeatherApiResponse> getWeatherByCityName(String cityName).
This result is always OK, because reactive-call-chain creation will always succeed.
What you need, is to make Hystrix threat Mono/Flux differently.
In Spring Cloud, there is a builder, to wrap Mono/Flux with HystrixCommand.
Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName);
Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands
.from(call)
.fallback(Mono.just(WeatherApiResponse.EMPTY))
.commandName("getWeatherByCityName")
.toMono();

Passing remote parameters in RMI

I would like to have confirm about RMI theory.
Let us suppose that Client A requests a remote reference of an object O to a Server B.
Well, now if In O interface (Interf) there is a method like:
void foo(Interf obj);
When Client A calls O.foo(O) it passes stub reference (before received ) and then Server does not use its local reference but the Stub Object (received by Client), and so each call on O methods by Server will make use of its TCP/IP service.
Is it Ok?
You should feel free to add some details if you think that those can improve my RMI understanding.
Regards
CORBA servers (as used to implement RMI/IIOP, not RMI/JRMP) typically implement a "colocated stub" optimization. That is, if a server invokes a method on a stub for an object that resides in that same process, the CORBA server will typically avoid TCP/IP and thread pool dispatch overhead. Instead, the parameters are copied, the method will be invoked on the target object, and the result object is copied and returned.
For reference, Java servers typically implement this optimization. The generated stub classes use the Util.isLocal method to determine if a stub target is local. Next, Stub._servant_preinvoke is called to obtain a reference/proxy to the local servant, and Util.copyObjects (or Util.copyObject) is used to copy parameters and return objects. (There are additional complexities with exception handling, RemarshalException, etc., but I've outlined the basic flow.)

Flex : Is it possible to stop a remote call?

I search for a long time, but I still not found the answer.
In common case, we keep the token of a remote method call, Flex -> Java for example.
But, if the client know that the current call is not needed anymore, how stopping the server processing ?
With an asyncToken, is it possible to stop a remote call ?
Thanks for your answer.
As I understood it, an AsyncToken just provides extra data for some operation. You'll need to access that operation to cancel.
IF you're calling an HTTPService, you use the cancel() method.
If you're using a WebService, you should be able to call getOperation() method and then cancel() the corresponding operation.
If you're using a RemoteObject you should be able to call getOperation() method and then cancel() on the corresponding operation.

How to Cache LINQ to SQL Results?

I'm using LINQ to SQL to call some reporting stored procedures.
Each stored procedure returns a class which accepts some input parameters, for example:
public partial class csp_WeekCommencingListResult
{
public static IEnumerable<csp_WeekCommencingListResult> GetAll(int? masterTrackingGroupId)
{
using (var dataContext = OscaDataContext.CreateWithCustomTimeOut())
{
return dataContext
.csp_WeekCommencingList(masterTrackingGroupId)
.ToList();
}
}
}
How could I cache the result of the stored procedure for the passed parameters?
For example, when 1 is passed to this stored procedure, its result should be cached for a day.
Any thoughts? is there any framework I can use? or I have to build my own custom cache manager per stored procedure using the .NET Cache object?
Thanks,
You should probably add caching at a higher level, for example in the code that is calling this code.
Try to figure out a good caching strategy that works with your project.
And when it comes to cache managers, I usually use the ICacheManager from Microsoft EnterpriseLibrary Caching which I property inject with some dependency injection framework like Castle or StructureMap. That way I can run different configurations for different environments (dev, test, prod etc).

WCF Exception Handling Strategies

We are developing a proxy in WCF that will serve as a means of communication for some handhelds running our custom client application. I am curious what error handling strategies people use as I would rather not wrap EVERY proxy call in try/catch.
When I develop ASP .NET I dont catch the majority of exceptions, I leverage Application_Error in Global asax which can then log the exception, send an email, and redirect the user to a custom error landing page. What I am looking for in WCF is similar to this, except that it would allow me to pass a general faultreason to the client from a central location.
Basically I am curious how people centralize their exception handling in WCF apps.
Thanks
You might find the IErrorHandler interface useful here. We've been using this to do pretty much what you mention - centralised exception logging and providing generalised fault reasons without having to litter the code with numerous try/catches to try and deal with the problem locally.
So here is what I did. We have a few custom exceptions in our application such as BusinessRuleException and ProcessException, WCF supports both FaultException and FaultException<T>.
General practice seems to be that you always throw FaultException to the client in the case of a general error or an error that you dont want to display exactly what happened. In other cases you can pass FaultException<T> where T is a class with information about the particular exception.
I created this concept of Violations in the application, which basically meant that any custom exception had a property containing the corresponding Violation instance. This instance was then passed down to the client enabling the client to recognize when a recoverable error had occured.
This solved part of the problem, but I still wanted a general catch all that would allow me to centeralize logging. I found this by using the IErrorHandle interface and adding my own custom error handler to WCF. Here is the code:
public class ServiceHostGeneralErrorHandler : IErrorHandler
{
public void ProvideFault(Exception ex, MessageVersion version, ref Message fault)
{
if (ex is FaultException)
return;
// a general message to the client
var faultException = new FaultException("A General Error Occured");
MessageFault messageFault = faultException.CreateMessageFault();
fault = Message.CreateMessage(version, messageFault, null);
}
public bool HandleError(Exception ex)
{
// log the exception
// mark as handled
return true;
}
}
Using this method, I can convert the exception from whatever it is to something that can be easily displayed on the client while at the same time logging the real exception for the IT staff to see. So far this approach is working quite well and follows the same structure as other modules in the application.
We use the Exception Handling Application block and shield most faults from clients to avoid disclosing sensitive information, this article might be a good starting point for you, as with "best practices" - you should use what fits your domain.