Background processing on C# web api controller - asp.net-web-api

I'm new on .NET technology and come into some problem. Currenlty i'm trying to build a REST API that handle long processing before sending the result to client.
What i'm trying to achieve is, i would like to do a background processing after receiving request from client. But, i would also like to send a response to client.
In short, it would be something like this.
Client Request -> Handled by controller ( doing some processing ) -> send response directly, ignoring the background that still running.
On Java, i can do this using Runnable Thread. How can i achieve this on C# Web API ?
Thank you.

In short, don't do this.
The job of an API is not to perform heavy duty, long running tasks.
You could simply let the API receive the request to perform something, then delegate that to another service. The API can then send a 200 response to show it received the request and maybe a URL to another resource which allows a user to track the progress.
The API needs to be available and responsive at all times. It needs to serve a number of users and if a number of them all request something that uses a lot of resources and takes a lot of time, chances are the API will simply go down and not serve anyone.
This is why you do not do such things in an API. Let other services do the heavy lifting.

Your api can call another async method and return 200/OK response without waiting for the request to complete.
You can learn more about async programing in c#.
static async Task Main(string[] args)
{
Console.WriteLine("coffee is ready");
var toastTask = MakeToastWithButterAndJamAsync(2);
async Task<Toast> MakeToastWithButterAndJamAsync(int number)
{
//Do something here.
}
}

This can be achieve this using loosed coupled architecture, by introducing service bus or blob storage, once you receive request in web api you can save it to blob/service bus and return acknowlegement response from web api. From service bus/blob storage use webjob/function/ durable function app to process the message using event.

Related

ColdFusion API and Websockets

I am hoping someone can point me in the right direction. I have a CF2021 Server which uses a Node.js websocket server and CF pages (via javascript) as a client. Messages from user to user work as expected, so no issue there.
This CF Server also has a custom API built using CFML that handles and routes inbound SMS messages. My question is; what would be the best way to send the SMS message (by now its json) to the Node.js websocket to it can send it to the user(s).
I tried using the same javascript that the browser client uses, but it appears that the CFML API script is "browser-less", so that doesn't work, or should it?
I thought something like Apache Groovy may be the solution, but I am having difficulties with any websocket example I have found.
Any suggestions would be greatly appreciated.
thanks in advance
Flow matters.
If you want to handle an incoming message by delivering it to all currently logged in users who are subscribed to messages of the current sort: set up your message handler to deliver using lucee/adobe-coldfusion websockets. Be forewarned, Lucee takes some setup time, but once running, it is a great solution.
If you don't need immediate delivery, or you need a super simple solution: I actually have had some success with "Long Polling" you just have to remember to use "flush" early in the request, before any pause/sleep, then loop your message lookup requests for new data, with a 1-5 second delay between each loop. Once new data is found, I like to return the request to the client, close that polling request and start a new polling request using the client side. I typically won't poll for more than 60 seconds. Even if the returned json object is empty.

API Gateway Proxy Integration. Return response of second lambda function

The premise is pretty simple.
The usual application flow is as follows:
API Gateway receives a request.
API Gateway triggers Lambda Function with parameters.
Lambda Function runs the logic.
The Lambda Function's response is automatically forwarded to API Gateway as the response to step 1 (Response to the Received API Request).
Here's the issue I'm having. I need to run two functions before returning the response to the received API request. I need the return statement from the second function in step 4 to be the response sent back
to the client.
Now there are more examples where this is necessary. In the future, we might need to run a few services (such as lambda > Lambda > PostgreSQL > API Response) before responding to the request.
Is there a way to receive a request from a client, then run a host of tasks, assemble the necessary data, then use this data as a response in the original API request? So far step-functions seemed a likely solution but I don't know if it can do this.
Until recently this would've been a pain with Step Functions but around re:invent time last year they announced the ability to orchestrate synchronous express workflows: https://aws.amazon.com/blogs/compute/new-synchronous-express-workflows-for-aws-step-functions/
IMO, this would be the best / easiest way to implement what you're looking for.

Android Management - How to send bulk request?

We have been using Android Management APIs to enroll devices in an enterprise and provide restricted environment to our users. We have a requirement where we need to bulk update all the devices by making a patch request using this API: https://developers.google.com/android/management/reference/rest/v1/enterprises.devices/patch
What I am looking for is that instead of sending requests one by one in an arbitrary fashion, is there any way I can send bulk requests and receive a response when all the devices are updated?
Note: I am already aware of how to do it one by one.
Help appreciated, thanks.
Use the AndroidManagement.batch() API to queue several requests for execution and reduce the connections your client makes. The now deprecated Google EMM API documentation has more information about this.
Here's a pseudo example on how to create a batch request, queue a device patch call and execute the request thereafter.
AndroidManagement amapi;
var batchRequest = amapi.batch();
amapi.enterprises().devices().patch(deviceName, content).queue(batchRequest, new JsonBatchCallback<>() {
#Override
public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) throws IOException {
}
#Override
public void onSuccess(com.google.api.services.androidmanagement.v1.model.Device device, HttpHeaders responseHeaders) throws IOException {
updateDevice(device);
}
});
// queue another device patch request...
// execute all queued requests
batchRequest.execute();
Please note that if you want to do a bulk update in order to save on the API usage limit, this will not help you. All requests in your batch will be counted separately when it comes to limits. There is no way around this.
Can you give more context about what you are trying to achieve? Perhaps what you want to do can be achieved with a policy. For example, to install an app on multiple devices, you could apply the same policy to those devices, and then add these lines to the policy:
"applications": [
{
"packageName": "com.google.samples.apps.iosched",
"installType": "FORCE_INSTALLED"
}
]
Regarding batch requests, here’s a sample code on how you can do batch requests in Android Management API.
def list_devices(request_id, response, exception):
"""Do something with the devices list response."""
if exception is not None:
# Do something with the exception.
pass
else:
# Do something with the response.
pass
get_device1 = androidmanagement.enterprises().devices().get(name=deviceName)
get_device2 = androidmanagement.enterprises().devices().get(name=deviceName)
batch = androidmanagement.new_batch_http_request();
batch.add(get_device1, list_devices)
batch.add(get_device2, list_devices)
batch.execute()
You may also check this link for more details about new_batch_http_request.
"You can use the batch() call on AndroidEnterprise and execute bulk requests by calling BatchRequest.execute().
Please note, you are limited to 1000 calls in a single batch request, so if you need to make more calls than that, use multiple batch requests.
Here's the format you can refer to: EMM API batch format.
Along with an example: EMM API batch example."

Detecting client disconnect with PushStreamContent in Web API

Although HTTP is a stateless protocol, there's this PushStreamContent class that facilitates server-sent events, as you can read here. A Web API implementation may store client streams and periodically send push updates. However, it's a bit of a problem to detect when the client disconnects.
In this discussion, Henrik Nielsen states that:
Detecting that the TCP connection has been reset is something that the Host (ASP, WCF, etc.) monitors but in .NET 4 neither ASP nor WCF tells us (the Web API layer) about it. This means that the only reliable manner to detect a broken connection is to actually write data to it. This is why we have the try/catch around the write operation in the sample. That is, responses will get cleaned up when they fail and not before.
In .NET 4.5 there is a mechanism for detecting client disconnect but I haven't tried it out.
Fast forward two and a half years to today. Does anyone have any idea what this mechanism is, and whether it works?
An interesting response was post on this link : link to the article
this is a part of the answer
In .NET 4.5 there is a mechanism for detecting client disconnect but I haven't tried it out.
This (simplified) code works for me:
public HttpResponseMessage Get(HttpRequestMessage request)
{
// Register for client disconnect notifications
object clientId = ...; // this is the object passed to the callback
System.Web.HttpContext.Current.Response.ClientDisconnectedToken.Register(
delegate (object obj)
{
// Client has cleanly disconnected
// obj is the clientId passed in to the register
// handle client disconnection
//...
}
, clientId );
// Normal code from the sample continues
response.Content = new PushStreamContent(...);
}
The ClientDisconnect callback is called back if e.g. you close the client browser page cleanly, but if you pull the network cable out, it does not get notified. So for this unclean disconnection, we still need some other way of detecting this, such as monitoring failures during the timer callback.

What is the name of the technique of holding open a web API call until new data is available, or the request times out?

I would like to research a technique for building Web API methods but I am having trouble looking up information on it partly because I do not know what the technique is called. The idea is that instead of the client polling the web API on a tight loop and taking action when the response data changes, instead the server holds the call open until it sees the data change and then completes the request. This is more efficient because less time is spent making web connections as each call from the client is utilized to it's full extent: if new data is available before the web API call's timeout is reached then the call can immediately return that new data.
What is this technique called?
Long polling. Not tried it myself yet.
http://en.wikipedia.org/wiki/Push_technology#Long_polling

Resources