Cancel Service Call - c#

I am using a WCF service, it is not an asynchronous service.
I do database operations in them. the Database operations return me huge result.
I want to provide a way to cancel the operation to my client.
Can anyone please suggest to achieve the same. I googled a lot
also could find out some soluions, some are saying to make the service operation as asynchronous.This is what I got from msdn
http://msdn.microsoft.com/en-us/library/ms731177(v=vs.110).aspx
But how do I stop it.
Also as I am new to this, I am not able to figure out the thing.
Can anyone please help me with this.
Thanks in advance.
Regards

You can keep your service synchronous but make async calls inside of your methods, around database queries for example. In this case you can use class Task which supports CancellationToken. But you should be on .NET 4 and up.

I you only want to cancel Service call (There is no session Locking (Session Creation/updation/deletion), you can make ajax call to service in javascript like :
var xhr;
var serviceUrl = "Service1.svc/GetData";
xhr= $.ajax({
type: "POST",
url: serviceUrl,
data: "{\"value\":\"request\"}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
//anything you need to do on success
}
});
For aborting request, you can do :
if(xhr && xhr.readystate != 4){
xhr.abort();
}
Please not that will abort the handler waiting for request & not request itself and if you are playing with Session(except for read), it will not work & wait for request to complete.
If you have above case, its better to use Task as mentioned by vzayko.
Also if you're using MVC 4, you can also use TAP(Task-based Asynchronous Pattern), which is specifically optimised for using tasks in ASP.net MVC.

Related

The equivalent of C# consuming a WCF method in JavaScript (jQuery)

I have a running WCF service that exposes a method GetStuff(String type). It's called by the automatically created client class, so the syntax is embarrassingly simple.
ServiceClient client = new ServiceClient();
String response = client.GetStuff("other's");
client.Close();
The straight-forward question is this. How do I convert that to a call in JavaScript (possiblyusing jQuery) in an easy way?
After some serious googling, I concluded that I'm only going to find examples of how to consume a JSON-formatted stream using jQuery. I prefer not to touch the service-side of the software, if at all possible.
I tried the code below (along with a bunch of derivatives that I could think of) but the error I got was "No Transport" and googling that didn't yield anything that I got me going.
$.ajax({
type: "GET",
url: "http://hazaa.azurewebsites.net/Service.svc",
success: function (response) { console.info(response); },
error: function (response) { console.error("Error! " + response.statusText); }
});
Will I have to write a totally different service that exposes the data in JSON format? How do I specify that the service is supposed to call this or that method? Am I out of luck and these convenience methods are for .NET clients only?
Please note that I've got another way of getting the data where I want, not using JavaScript at all but I'd prefer to see if this is (easily) doable too.
I would convert server method to use web invocation = WebInvoke attribute. Here you can specify uri for the method call.
Link to the info
Look into Jquery SOAP .. http://plugins.jquery.com/soap/ etc.
haven't tried it myself but it's the kind of thing you might be needing here.

Update label while a method is running

How do I update a label in a aspx page while a method is running? Perhaps using AJAX (update panel)?
private void button_Click(object sender, EventArgs e)
{
doThings1();
label.Text = "Status1";
doThings2();
label.Text = "Status2";
doThings3();
label.Text = "Done";
}
I want to show step by step. While the method is running when the doThings1() is done, shows "Status1", doThings2() is done, shows "Status2"... In this way, the label doesn't show "Status1" and "Status2", just "Done" when the process is finished. I'd like to show step by step.
This is not an easy thing to do, the way it is in a desktop application. You need to start an asynchronous operation that will continue after the request ends, you'll need to have the client continually poll the server for updates as to the progress, and the server side asynchronous code will need to update some sort of share state (i.e. session, a database, view state, etc.) that the polling method can read the progress from. All around it's quite inefficient (especially if you have a lot of users doing this) and takes some time to write. Here is an example on MSDN that does this, to give you an idea of what's involved.
The rule is: 1 request --> one response.
Different approach:
You can these methods execute with 3 asyncron javascript call and set the labels' text at the success callback.
http://api.jquery.com/jQuery.ajax/
Example:
$.ajax({
type: "POST",
url: "URL.asmx/doThings1",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
// result will be "done" from the function of webservice below.
// set the first label text
},
error: function(xmlHttpRequest, status, err) {
alert(xmlHttpRequest.statusText + " " + xmlHttpRequest.status + " : " + xmlHttpRequest.responseText);
}
});
Repeat these calls 3 times and do your modifications in different functions.
You can handle your buttonclick at client side with jquery or pure javascript.
You can use a webservice or generic handler to execute server side methods.
How to create webservice
[WebMethod]
public string doThings1()
{
return "done";
}
It sounds like you want to show the progress of some task that is running on the server. The signalr library will allow you to send real time updates to the client from the server. So anytime the task completed a stage (Status1, Status2, etc) of the task, it would send an update to the listening clients with the new status.
You could also have some javascript request the task status from the server every few seconds and display it to the user.

how to get Asynchronous response to an Ajax request? [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
ASP.NET Server does not process pages asynchronously
There is a question regarding Asynchronous response to an Ajax request.
I’m working on a web application to enable some simple image processing actions for user, using ASP.Net + Ajax. As most of image processing actions takes a while to accomplish, we’d like to utilize user to send the request to the server through Ajax, and get the partial response immediately, while the server is processing and to send completed response in a later time (i.e. 10/20 seconds later for instance).
This way, I suppose the server should be able to push the late response (which obtained 10/20 seconds later) to the client.
Is there any idea how to realize such interaction?
The closest thing you'll get is JSONP, which can be used with jQuery.
like:
$.ajax({
type: 'GET',
url: 'http://api.stackoverflow.com/1.1/tags/ravendb/wikis',
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
jsonp: 'jsonp'
async: true,
success: function (data) {
if (data.tag_wikis.length > 0) {
alert(data.tag_wikis[0].wiki_excerpt);
}
},
});

jquery "async = true" call to .net web service not working asynchronously

I have a .NET webservice which I need to hit asynchronously from the jQuery and update the grid based on the result got from service. My problem here is that, the service hit is async only for the first time and the subsequent requests are sync (even after specifying async=true in the ajax call) as shown below
jQuery.ajax({
type: "POST",
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) {
var result = msg.d;
return callback(result);
},
error: $.callDotNetSM.onError
});
My .NET service method is something like below.
[WebMethod(EnableSession = true)]
public static string GetData()
{
}
So, please help me in calling the service asynchronously all the times. Any help is highly appreciated.
The page your WebMethod is being called on needs to have the following in the Page Directive:
<%# Page Async="true" EnableSessionState="False" %>
The reason for this is that ASP.NET locks the Session every time it is accessed so that it cannot run asynchronously.
Even if you do not use the Session in your WebMethod the page still thinks it uses it by default unless you tell it otherwise.
Edit:
Your problem could also be that you have EnableSession="true". You may just need to set it to false.

Time out Ajax requests with jquery?

I think that you can set like on post and get methods in jquery timeouts but I am wondering does jquery have a global timeone like it has with ajax start and stop.
Like I would like to set it that if say a post or get or some sort of ajax request is running and it runs more then X amount of seconds. That a popup or something in that nature comes up saying that the "server is slow and the request has timed out" and kills that request.
Then the user can either try again or do something else.
Does jquery have something like this?
Thanks
The jQuery.ajax function is what you want. It gives you access to a pretty large set of options for making AJAX calls.
Specifically, you're going to want to make a call similar to
$.ajax({'complete': callbackFunction, 'url': 'foo/bar/', 'timeout': 5000, 'error': errorCallback});
The two options you're interested in are timeout and error. The entire documentation for the function is here. It's a bit more work than using the more standard get/post functions, but much more flexible.
The error function is very similar to the standard callback you use with any jQuery AJAX request. While the callback is called if the request succeeds, the error function is called when it fails (such as 404 errors, or when the timeout is hit). You'd use the error function to display your message to the user that their request has timed out. Full documentation on the function's arguments (which practically speaking, you probably won't need to use) is available on the $.ajax doc page (linked earlier).
Alternatively, you can set the timout globally on every AJAX call by using the jQuery.ajaxSetup function. Its arguments are exactly the same as the jQuery.ajax function, so you'd do something like this:
$.ajaxSetup({'timeout': 5000, 'error': errorCallback});
The upside is that you can continue using jQuery.get/jQuery.post, but the downside is that you have to do extra work to make AJAX calls without a timeout.
Yep, jQuery has a 'timeout' property (in milliseconds) you send the $.ajax() event:
http://www.bennadel.com/blog/1500-Catching-Timeout-Errors-With-jQuery-Powered-AJAX.htm
$.ajax(
{
method: "get",
url: "yourpage.php",
dataType: "json",
timeout: (3 * 1000), // 3 seconds
success: function(){
//success code here
},
error: function( request, strError ){
//error code here
}
}
);

Categories