Stoping web service in flex? - apache-flex

is it possible to stop a web service from executing?
I have a flex web application that searches clients with both full name and client id, when searching by name sometimes the usuer just types the last name and it takes a long time.
Since the app is used when clients are waiting in line, I would like to be able to stop the search and use their full name or id instead, and avoid waiting for the results and then having to search the user manually within the results.
thanks
edit: Sorry, I didn't explain myself correctly, when I meant "web service" I actually meant mx.rpc.soap.mxml.WebService, I want to stop it from waiting for the result event and the fault event. thanks.

There is actually a cancel(..) method explicitly for this purpose, though it is a little burried. Using the cancel method will cause the result and fault handlers not to be called and will also remove the busy cursor etc.
Depending on how you run your searches (ie. separate worker process etc), it is also possible to extend this by added in a cancelSearch() web service method to kill these worker processes and free up server resources etc.
private var _searchToken:AsyncToken;
public function doSearch(query:String):void
{
_searchToken = this.searchService.doSearch(query);
}
protected function doSearch_resultHandler(event:ResultEvent):void
{
trace("doSearch result");
trace("TODO: Do stuff with results");
_searchToken = null;
}
protected function doSearch_faultHandler(event:FaultEvent):void
{
trace("doSearch fault: " + event.fault);
_searchToken = null;
}
public function cancelSearch():void
{
var searchMessageId:String = _searchToken.message.messageId;
// Cancels the last service invocation or an invokation with the
// specified ID. Even though the network operation may still
// continue, no result or fault event is dispatched.
searchService.getOperation("doSearch").cancel(searchMessageId);
_searchToken = null;
trace("The search was cancelled, result/fault handlers not called");
// TODO: If your web service search method is using worker processes
// to do a search and is likely to continue processing for some time,
// you may want to implement a 'cancel()' method on the web service
// to stop any search threads that may be running.
}

Update
You could use disconnect() to remove any pending request responders, but it also disconnects the service's connection. Then call initialize().
/Update
You cannot stop the web service from executing, because that's beyond the Flex app's control, but you can limit the processing of the web service's response. For instance on the app, have a button like Cancel Search which sets a boolean bSearchCanceled to true.
The result handler for the web service call checks bSearchCanceled; if true just return.

Related

gRPC Java Client - hasNext during onNext?

I have a server-side streaming gRPC service that may have messages coming in very rapidly. A nice to have client feature would be to know there are more updates already queued by the time this onNext execution is ready to display in the UI, as I would simply display the next one instead.
StreamObserver< Info > streamObserver = new StreamObserver< info >( )
{
#Override
public void onNext( Info info )
{
doStuffForALittleWhile();
if( !someHasNextFunction() )
render();
}
}
Is there some has next function or method of detection I'm unaware of?
There's no API to determine if additional messages have been received, but not yet delivered to the application.
The client-side stub API (e.g., StreamObserver) is implemented using the more advanced ClientCall/ClientCall.Listener API. It does not provide any received-but-not-delivered hint.
Internally, gRPC processes messages lazily. gRPC waits until the application is ready for more messages (typically by returning from StreamObserver.onNext()) to try to decode another message. If it decodes another message then it will immediately begin delivering that message.
One way would be to have a small, buffer with messages from onNext. That would let you should the current message, and then check to see if another has arrived in the mean time.

Cosmo ChangeFeed -Errors,exceptions and Service fail scenario's

All,
I am using Change Feed Processor Library.Want to know the best way to handle service failure along with the exceptions/errors scenario's in ProcessChangesAsync method. Below are the events am referring to.
1) Service failure - Service having the processor library crashed in the middle of some operation. How to start the process from the same document(doc on failure instance)? is there any inbuilt mechanism where change feed will start with the last failed documents? E.g. Let assume,in current batch we have 10 docs.5 processed successfully and then service breaks because of network failure or by some other reasons.Will my process starts with 6th document once service is re-started? How to achieve this?
2) Exception and Errors- Any errors in ProcessChangesAsync method can be handle using try catch at the global level but how to persist those failure records and make them available for the next batch? Again,looking for any available inbuilt mechanism in change feed process.
1) The Processor Library, by default, checkpoints after a successful run of ProcessChangesAsync. In the latest library version, you can customize the Checkpointer to do manual checkpoints in case you need it. If for some reason the processor shuts down before checkpointing, then it will start processing next from the the last successful checkpoint stored in the Leases collection. In your case, it will start with the first document again, so you will never lose a change but you could experience double processing (this is an "at least once" model).
2) There is no built-in mechanism that you can leverage, handling exceptions within the ProcessChangesAsync is your responsibility. You could not only add a global try/catch but, in the case you are looping over the documents, add a try/catch inside the loop, to handle a failing document (maybe send it to queue for later analysis/post-process) without losing the batch. If you require logging for those errors (I'm assuming that's what you mean by persisting errors?), then the latest version is compatible with LibLog, so plugging your own custom logging is as simple as:
using Microsoft.Azure.Documents.ChangeFeedProcessor.Logging;
var hostName = "SampleHost";
var tracelogProvider = new TraceLogProvider(); //You can use any provider supported by LibLog
using (tracelogProvider.OpenNestedContext(hostName))
{
LogProvider.SetCurrentLogProvider(tracelogProvider);
// After this, create IChangeFeedProcessor instance and start/stop it.
}
Source
Extra info for the comments
To avoid exceptions halting the batch or causing a batch to be reprocessed, you can have handling like this:
public async Task ProcessChangesAsync(IChangeFeedObserverContext context, IReadOnlyList<Document> documents, CancellationToken cancellationToken)
{
try
{
foreach(var document in documents)
{
try
{
// Do your work for the document
}
catch(Exception ex)
{
// Something happened with the current document, handle it, send it to a queue / another storage to analyze, log it. This catch will make the loop continue with the next.
}
}
}
catch(Exception ex)
{
// Something unhandled happened, log it and avoid throwing it again so the next batch is processed
}
}

Need advice in develop a queue job to interact between two application

Currently i have a web application and a wins form application in my server. Basically, the web application will receive request from user and this request will be send to the wins form application to proceed (wins form need about 1 minute to complete a request).
Let say 2 users send a request at the same time via web application, I need to develop a queue job to maintain the request in sequence.
1) User A make a request > request will be store into a queue job
2) User B make a request > request will be store into a queue job
3) The queue job will send the first request to the wins form. Once first request is complete, then will follow by the second request
So my question is, this queue job should be develop inside the web application? Or it should be develop in a stand alone wins form?
Any example code for create a queue job in ASP.NET?
Or anyone can suggest a better solution?
using System.Collections.Generic;
Queue<task> Q = new Queue<task>();
public void Proccess_Request(string info)
{
task t = new task();
t.INFO = info;
Q.Enqueue(task);
}
public void DoWork()
{
//
while (Q.Count > 0)
{
task t = Q.Dequeue();
//Process task t
}
}
public class task
{
public string INFO { get; set; }
// Whatever task properties you need
}
You will need to build the service that accepts form data and passes it to method Process_Request. You will also need to call method DoWork either once every x minutes, or have it listen for Process_Request to fire.
Or you can use MSMQ and do it that way. the ASP.NET site sends a message to the queue, the winforms app (or service) is bound to the queue so when messages come into the queue, it will pick it up, process it and let it be done until no more messages in the queue.
You can handle cross domain queue communication with MSMQ, for example.

Display output from command line program realtime in asp.net

I am writing a web app where the application runs a command on the system using System.Diagnostics class.
I wanted to display realtime output from a command which takes a lot of time to complete. After searching a bit, I found that BeginOutputReadLine can stream output to an event handler.
I am also using jquery ajax to call this method and have the process run asynchronously.
So far, I am trying to do it this way:
Process p2= new Process();
p2.OutputDataReceived += new DataReceivedEventHandler(opHandler);
p2= Process.Start (psi2);
p2.BeginOutputReadLine();
I have declared a class with a static variable to store the output of the command as a Label on the page wont be accessible from a static method.
public class ProcessOutput
{
public static string strOutput;
[WebMethod]
public static string getOutput()
{
return strOutput;
}
}
In the event handler for BeginOutputReadLine, set the variable with the line from output.
private static void opHandler(object sendingProcess,DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data))
{
ProcessOutput.strOutput= outLine.Data;
}
}
and from the aspx page, I am calling the method to get the value of strOutput
$(document).ready(function() {
setInterval(function() {
$.ajax({
type: "GET",
url: "newscan.aspx/getOutput",
data: "",
success: function(msg){
$('#txtAsyncOp').append(msg.d);
}
});
}, 1000);
});
I dont know why, but the lable is not getting updated. If I put alert, I get 'undefined' in the alert box every 10 seconds.
Can anybody suggest me how to do it correctly?
Each request begins a new thread as a part of the Request pipeline. This is by design. Each thread has its own stack and can't access each others stacks. When a thread starts running a new method it stores the arguments and local variables in that method on its own stack. Long story short you won't be able to assign that variable and expect to retrieve its value from another Request.
There are a couple approaches you can take, you can scope it to the session variable (most common) with:
System.Web.HttpContext.Current.Session["variable"] = value ;
Or you set it to application scope using:
if (System.Web.Caching.Cache["Key1"] == null)
System.Web.Caching.Cache.Add("Key1", "Value 1", null, DateTime.Now.AddSeconds(60), Cache.NoSlidingExpiration, CacheItemPriority.High, onRemove);
Alternatively, you can log the output to a database or file and echo out the results via the WebMethod. If your long running process is running asynchronously, you won't have access to the HttpContext -- so the Session state bag will not be available; the application Cache could be used, however it is generally not used for this type of mechanism (cache is available for performance reasons, not a persistence mechanism -- its important to remember that you cannot control when your web application recycles).
I'd highly suggest writing to a database or log file. Asynchronous processes commonly require logged output or trace to diagnose potential problems and to validate results.
Furthermore, because you cannot control when the web app recycles, you can easily lose control of that child process you're launching. A better design would start an asynchronous method in-process, or an out-of-process application or service that polls a database to pick up jobs (possibly use the task scheduler or cron depending on your platform).

ASP.Net Web Service: Running code Asynchronously

I have a web service that can be broken down into two main sections:
[WebMethod]
MyServiceCall()
{
//Do stuff the client cares about
//Do stuff I care about
}
What I'd like to do is run that 2nd part on another thread, so that the client isn't waiting on it: once the user's logic has completed, send them their information immediately, but continue processing the stuff I care about (logging, etc).
From a web service, what is the recommended way of running that 2nd piece asynchronously, to get the user back their information as quickly as possible? BackgroundWorker? QueueUserWorkItem?
You may want to look into Tasks which are new to .NET 4.0.
It lets you kick off an asynchronous operation, but also gives you an easy way to see if it's done or not later.
var task = Task.Factory.StartNew(() => DoSomeWork());
It'll kick off DoSomeWork() and continue without waiting so you can continue doing your other processing. When you get to the point where you don't want to process anymore until your asynchronous task has finished, you can call:
task.Wait();
Which will wait there until the task has completed. If you want to get a result back from the task, you can do this:
var task = Task.Factory.StartNew(() =>
{
Thread.Sleep(3000);
return "dummy value";
});
Console.WriteLine(task.Result);
A call to task.Result blocks until the result is available.
Here's a tutorial that covers Tasks in greater detail: http://www.codethinked.com/net-40-and-systemthreadingtasks
The easiest way to fire off a new thread is probably:
new Thread(() =>
{
/// do whatever you want here
}).Start();
Be careful, though - if the service is hit very frequently, you could wind up creating a lot of threads that block each other.

Resources