Calling WCF operation that has no return value asynchronously - wcf

I have a long running operation:
void LongRunningOperation(string someValue);
How do i call it asynchronously (I want a fire and forget mechanism)?

you can set the mode to oneway.
you do not require to call these methods asynchronously. call to the methods returns as soon as they are call if the mode is one way.
use:
[OperationContract(IsOneWay = true)] attribute to describe your operation contract.

Assuming that you have already configured your proxy to the service, you will need to do the following (in VS):
Open your project that references the service, then go to service references.
Right-click the relevant service reference and select 'Configure Service Reference' from the context menu.
Tick the box that says 'Generate asynchronous operations'
After your client code regenerates, you will see a method that says BeginLongRunningOperation; that's your async method.

Related

ServiceStack: Reinstate pipeline when invoking a Service manually?

As a follow-up to this question, I wanted to understand how my invoking of a Service manually can be improved. This became longer than I wanted, but I feel the background info is needed.
When doing a pub/sub (broadcast), the normal sequence and flow in the Messaging API isn't used, and I instead get a callback when a pub/sub message is received, using IRedisClient, IRedisSubscription:
_subscription.OnMessage = (channel, msg) =>
{
onMessageReceived(ParseJsonMsgToPoco(msg));
};
The Action onMessageReceived will then, in turn, invoke a normal .NET/C# Event, like so:
protected override void OnMessageReceived(MyRequest request)
{
OnMyEvent?.Invoke(this, new RequestEventArgs(request));
}
This works, I get my request and all that, however, I would like it to be streamlined into the other flow, the flow in the Messaging API, meaning, the request finds its way into a Service class implementation, and that all normal boilerplate and dependency injection takes place as it would have using Messaging API.
So, in my Event handler, I manually invoke the Service:
private void Instance_OnMyEvent(object sender, RequestEventArgs e)
{
using (var myRequestService = HostContext.ResolveService<MyRequestService>(new BasicRequest()))
{
myRequestService.Any(e.Request);
}
}
and the MyRequestService is indeed found and Any called, and dependency injection works for the Service.
Question 1:
Methods such as OnBeforeExecute, OnAfterExecute etc, are not called, unless I manually call them, like: myRequestService.OnBeforeExecute(e) etc. What parts of the pipeline is lost? Can it be reinstated in some easy way, so I don't have to call each of them, in order, manually?
Question 2:
I think I am messing up the DI system when I do this:
using (var myRequestService = HostContext.ResolveService<MyRequestService>(new BasicRequest()))
{
myRequestService.OnBeforeExecute(e.Request);
myRequestService.Any(e.Request);
myRequestService.OnAfterExecute(e.Request);
}
The effect I see is that the injected dependencies that I have registered with container.AddScoped, isn't scoped, but seems static. I see this because I have a Guid inside the injected class, and that Guid is always the same in this case, when it should be different for each request.
container.AddScoped<IRedisCache, RedisCache>();
and the OnBeforeExecute (in a descendant to Service) is like:
public override void OnBeforeExecute(object requestDto)
{
base.OnBeforeExecute(requestDto);
IRedisCache cache = TryResolve<IRedisCache>();
cache?.SetGuid(Guid.NewGuid());
}
So, the IRedisCache Guid should be different each time, but it isn't. This however works fine when I use the Messaging API "from start to finish". It seems that if I call the TryResolve in the AppHostBase descendant, the AddScoped is ignored, and an instance is placed in the container, and then never removed.
What parts of the pipeline is lost?
None of the request pipeline is executed:
myRequestService.Any(e.Request);
Is physically only invoking the Any C# method of your MyRequestService class, it doesn't (nor cannot) do anything else.
The recommended way for invoking other Services during a Service Request is to use the Service Gateway.
But if you want to invoke a Service outside of a HTTP Request you can use the RPC Gateway for executing non-trusted services as it invokes the full Request Pipeline & converts HTTP Error responses into Typed Error Responses:
HostContext.AppHost.RpcGateway.ExecuteAsync()
For executing internal/trusted Services outside of a Service Request you can use HostContext.AppHost.ExecuteMessage as used by ServiceStack MQ which applies Message Request Request/Response Filters, Service Action Filters & Events.
I have registered with container.AddScoped
Do not use Request Scoped dependencies outside of a HTTP Request, use Singleton if the dependencies are ThreadSafe, otherwise register them as Transient. If you need to pass per-request storage pass them in IRequest.Items.

Proxy generated for WCF creating Message Contracts

I'm consuming a WCF service in my project for which I've added the reference using 'Add Service Reference...'. I expected it to generate a clean proxy with a ServiceClient entity and the Interface. Instead, I see that it has created a MethodNameRequest, MethodNameRequestBody, MethodNameResponse, MethodNameResponseBody entities for each OperationContract method.
So while invoking the service methods, the proxy passes to the service method an instance of MethodNameRequest with the input parameters of the method as the properties of the RequestBody. See below an example of a call to AboutInformationGet() method which doesn't accept any parameters.
public WCFDynamicInvocation.PostingService.AboutModel AboutInformationGet() {
WCFDynamicInvocation.PostingService.AboutInformationGetRequest inValue = new WCFDynamicInvocation.PostingService.AboutInformationGetRequest();
inValue.Body = new WCFDynamicInvocation.PostingService.AboutInformationGetRequestBody();
WCFDynamicInvocation.PostingService.AboutInformationGetResponse retVal = ((WCFDynamicInvocation.PostingService.IMIGQPosting)(this)).AboutInformationGet(inValue);
return retVal.Body.AboutInformationGetResult;
}
I believe this behavior is what one would expect to see in a Webservice Proxy. Hence I suspect that the WCF service is not properly configured.
Did someone here face this issue? What would be the change to be done at the service so that the proxy generated is similar to the WCF service.
Cheers.
There is a similar post here.
Right click your service reference -> Configure service reference... -> Check if "Always generate message contracts" check box is checked. Uncheck it and hit OK to regenerate the proxy to see if you get a normal proxy.
After struggling with this for some time, I've finally found that the cause for the message contracts in the proxy was the service interface had the following attribute:
[XmlSerializerFormat(Use = OperationFormatUse.Literal, Style = OperationFormatStyle.Document)]
As I understand, I could decorate the DataContracts with the following attribute to avoid wrapping
[MessageContract(IsWrapped = false)]
but the response still gets wrapped as the OperationContract hasn't been modified.
As there were no particular need to use XMLSerializer in place of WCF's default DataContractSerializer, we would remove the XmlSeralizerFormat decoration.

Can WCF be auto scheduled?

I have below requirements:
(1) Perform 'action A' when user requests for it.
(2) We also want to perform the same 'Action A' twice in a day even if users don't request for it.
I have a WCF web service which has method XYZ that performs action A. The method XYZ will be called when user requests for it.
Now question is, can I schedule this action without creating window service (which can host this service) or creating proxy?
Is there a way to perform an action by user request and schedule that same action, using only one application?
No, WCF cannot be auto-scheduled. You need to implement a Scheduled Task (see Scheduling jobs on windows), a Windows Service with a timer (which you've said you don't want to do, if I understand correctly) or some other application with a timer.
You could start a thread as per the other answer but this relies on your service calling itself - I'd prefer to call it externally, from another process.
A scheduled task can run an executable. You could write a console application that calls your WCF service, logs any result (if necessary) and then completes.
I normally prefer to implement this type of timer through a Windows Service, simply because the Windows Service can be monitored, can log, and can auto-start / auto-restart - install it and it 'just works'. If I didn't want to use a Windows Service then I'd schedule a task.
I typically do this by just calling the WCF service method from some kind of task scheduler. In a really simple form, you could just spawn a Thread from your service, that runs the WCF method periodically. Again this isnt the best solution, but its easiest to demonstrate. You could use some other scheduler library to do this too...
[ServiceContract]
public class SomeClass
{
[ServiceOperation]
public void SomeServiceMethod() { ... }
Then somewhere in the application startup:
Thread t = new Thread(new ThreadStart(CallService));
t.Start();
...
// this will call the WCF service method once every hour
public void CallService()
{
Thread.Sleep(3600000); // sleep 1 hour
new SomeClass().SomeServiceMethod();
}
This is one way to do it, although not the best way, but basically you can just call the WCF service method just like any other method in the application.

How can I disable MessageInspector of my condition

I inpesct WCF Service With IDisptachMessageInspector and then I call service operation at BeforeSendReply Method which changes context of message. But it when I call service , Inspector runs again. I want to not run inspector. Do you know any way to do that scenerio?
The purpose of a message inspector is to allow you to modify the message before or after the rest of the service model layer processes it
BeforeSendReply is called after the operation has been invoked already, AfterReceiveRequest is called before the operation is invoked.
The behavior you are seeing is that your message inspector is being fired after the operation. You are then firing another operation which then ends up calling your message inspector again. BeforeSendReply is often used to manipulate the response message to some format that WCF has problems with generating using its default serialization, etc. Its not going to be able to give you the behavior you are looking for
To decide on which operation is invoked you normally implement an IDispatchOperationSelector. The specific idea of this extension point looks like it will be exactly what you need
Answer is implementing IOperationInvoker

Detect when client connected to wcf service

From a little bit of reading around, it is my understanding that the only way to detect that a client has connected to my service is through writing my own code. I am using a Singleton service. I would like to display a message every time a client connects to my service that client x with ip xxx has connected. There is no built-in event that is generated? Am I correct?
No, I don't think there's any support in WCF for your requirement.
Not sure what you want to achieve with this, either. Your service class (in your case, just a single instance) really doesn't have any business putting up messages (on screen, I presume) - that really not it's job. The service class is used to handle a request and deliver a response - nothing more.
The ServiceHost class might be more of a candidate for this feature - but again, it's job really is to host the service, spin up the WCF runtime etc. - and it's really not a UI component, either.
What you could possibly do is this
have an Admin UI (a Winforms, console, or WPF app) running on your server alongside your service, providing an admin service to call
define a fast connection between the two services (using e.g. netNamedPipe binding which is perfect for intra-application messaging)
when your "real" service gets a call, the first thing it does is send out a message to the admin UI which can then pick up that message and handle it
That way, you could cleanly separate your real service and it's job (to provide that service) and the Admin UI stuff you want to do and build a cleanly separated system.
I have actually implemented my own connect, disconnect and ping service methods which I manually call from my client once the channel has been created. By using them as a kind of header section in all of my ServiceContract interface definitions (and their implementations, of course), they form an makeshift "base service definition" that only requires a bit of cut-n-paste.
The string-based parameters of connect and disconnect will be used to send client info to the server and return server info and (perhaps a unique connection id) to the client. In addition a set of timing reference points may make its way in also.
Note how SessionMode is required and the individual OperationContract properties IsInitiating and IsTerminating are explicitly specified for each method, the end result being what I would call a "single-session" service in that it defines connect and disconnect as the sole session bookends.
Note also that the ping command will be used as the target of a timer-based "heartbeat" call that tests the service connection state and defeats ALL connection timeouts without a single config file :-)
Note also that I haven't determined my fault-handling structure yet which may very well add a method or more and/or require other kinds of changes.
[ServiceContract( SessionMode = SessionMode.Required )]
public interface IRePropDalSvr {
[OperationContract( IsInitiating=true, IsTerminating=false )]
string connect (string pClientInfo);
[OperationContract( IsInitiating=false, IsTerminating=true, IsOneWay=true )]
void disconnect (string pClientInfo);
// ------------------------------------------------------------------------------------------
[OperationContract( IsInitiating=false, IsTerminating=false )]
string ping (string pInp);
// ------------------------------------------------------------------------------------------
// REST OF ServiceContract DEFINITION GOES HERE
One caveat: while I am currently using this code and its implemention in my service classes, I have not verified the code yet.