c# How to exit from an application .exit() ExitThread() dont seem to work - exit

I have a very simple application which launches another class which contains a tray nottification
class Program
{
[STAThread]
static void Main(string[] args)
{
// Once it successfuly connects with the WCF , we can start the
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new AgentTray());
Application.Exit();
here the code for the second class
public class AgentTray : ApplicationContext , IWcfServiceCallback
{
public AgentTray()
{
......
this.ExitThread();
Application.Exit();
I run it in debug mode and I see that from AgentTray the two Exit commands are executed but the application still keeps running. In fact I put a breakpoint in the Application.Exit in the main method and the execution flow never reach that point.
Any idea what might be happening?

Related

Preventing a WCF client from issuing too many requests

I am writing an application where the Client issues commands to a web service (CQRS)
The client is written in C#
The client uses a WCF Proxy to send the messages
The client uses the async pattern to call the web service
The client can issue multiple requests at once.
My problem is that sometimes the client simply issues too many requests and the service starts returning that it is too busy.
Here is an example. I am registering orders and they can be from a handful up to a few 1000s.
var taskList = Orders.Select(order => _cmdSvc.ExecuteAsync(order))
.ToList();
await Task.WhenAll(taskList);
Basically, I call ExecuteAsync for every order and get a Task back. Then I just await for them all to complete.
I don't really want to fix this server-side because no matter how much I tune it, the client could still kill it by sending for example 10,000 requests.
So my question is. Can I configure the WCF Client in any way so that it simply takes all the requests and sends the maximum of say 20, once one completes it automatically dispatches the next, etc? Or is the Task I get back linked to the actual HTTP request and can therefore not return until the request has actually been dispatched?
If this is the case and WCF Client simply cannot do this form me, I have the idea of decorating the WCF Client with a class that queues commands, returns a Task (using TaskCompletionSource) and then makes sure that there are no more than say 20 requests active at a time. I know this will work but I would like to ask if anyone knows of a library or a class that does something like this?
This is kind of like Throttling but I don't want to do exactly that because I don't want to limit how many requests I can send in a given period of time but rather how many active requests can exist at any given time.
Based on #PanagiotisKanavos suggjestion, here is how I solved this.
RequestLimitCommandService acts as a decorator for the actual service which is passed in to the constructor as innerSvc. Once someone calls ExecuteAsync a completion source is created which along with the command is posted to the ActonBlock, the caller then gets back the a Task from the completion source.
The ActionBlock will then call the processing method. This method sends the command to the web service. Depending on what happens, this method will use the completion source to either notify the original sender that a command was processed successfully or attach the exception that occurred to the source.
public class RequestLimitCommandService : IAsyncCommandService
{
private class ExecutionToken
{
public TaskCompletionSource<bool> Source { get; }
public ICommand Command { get; }
public ExecutionToken(TaskCompletionSource<bool> source, ICommand command)
{
Source = source;
Command = command;
}
}
private IAsyncCommandService _innerSrc;
private ActionBlock<ExecutionToken> _block;
public RequestLimitCommandService(IAsyncCommandService innerSvc, int maxDegreeOfParallelism)
{
_innerSrc = innerSvc;
var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = maxDegreeOfParallelism };
_block = new ActionBlock<ExecutionToken>(Execute, options);
}
public Task IAsyncCommandService.ExecuteAsync(ICommand command)
{
var source = new TaskCompletionSource<bool>();
var token = new ExecutionToken(source, command);
_block.Post(token);
return source.Task;
}
private async Task Execute(ExecutionToken token)
{
try
{
await _innerSrc.ExecuteAsync(token.Command);
token.Source.SetResult(true);
}
catch (Exception ex)
{
token.Source.SetException(ex);
}
}
}

Update an instance variable in BPS

Using WSO2 BPS 3.6.0 - is there a (standard) way to update an instance variable in an already running instance?
The reason behind is - the client passes incorrect data at the process initialization, the client may fix its data, but the process instance remembers the wrong values.
I believe I may still update a data in the database, but I wouldn't like to see process admins messing with the database
Edit:
I am working with the BPEL engine and my idea is to update a variable not from a process design, but as a corrective action (admin console? api?)
Thank you for all ideas.
You are setting the instance variables during process initialization based on client's request.
For your requirement, where the variables need to be retrieved for the request. You can do this by using the execution entity to read the data instead of the instance variables that were set during process initialization.
Refer example below :
public class SampleTask implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
String userId = execution.getVariable("userId");
//perform your logic here
}
}
If you want to keep using the instance variables, I suggest you to change the instance variable during the process execution.
public class SampleTask implements JavaDelegate {
private String userId;
public void execute(DelegateExecution execution) throws Exception {
String newUserId = execution.getVariable("userId");
setUserId(newUserId);
//perform your logic here
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
}

Windows RPC object marshalling

I'm trying to use Windows RPC for communcation between two processes (C/C++, 32bit, Win7).
I've followed the example here Instruction to RPC and successfully got RPC to work. Now I have difficulties getting the proxy / stub thing to work too.
The IDL file looks like this:
[ uuid(3cb112c0-688a-4611-83b6-31d33d87ea28), object ]
interface IDemo : IUnknown
{
HRESULT ThisIsAMethod([in, string] const char* test);
}
[ uuid(60ad6a21-ba49-483a-b0a2-faa5187b8299), version(1.0),
implicit_handle(handle_t hDemoBinding)]
interface IDemoRPC
{
void SimpleTest();
void GetDemo([out] IDemo** service);
void Shutdown();
}
I can invoke SimpleTest() remotely on the server from the client. Works just fine. But GetDemo() gives me an access violation when the server 'returns' something else than NULL.
Here's what I've done:
Build a DLL based on the generated demo_i.c, demo_p.c, dlldata.c. With REGISTER_PROXY_DLL set and a def file containing the five private entries. I've registered it with regsvr32 (the one from WOW64).
Created a DemoImpl class in the server process that extends IDemo and implements ThisIsAMethod as well as AddRef and friends.
Implemented GetDemo(IDemo** service) with a one-liner *service = new DemoImpl();
When I invoke GetDemo from the client process, the server process terminates with an access violation (0x00000014). The stacktrace shows that it happens in a separate thread deep within rpcrt4.
I would have expected that the thing returns a proxy to the client.
I have the suspicion that I'm doing something fundamentally wrong here. For one thing, I can't find an example where instances of interface-objects are created with new. There always some some magic with CoGetClassObject or something. No clue how these functions should know where to find the implementation.

Usage of send and receive task in camunda BPMN

I am using a send task to which the following Javadelegate class is attached.
public class SendTaskDelegate implements JavaDelegate {
public void execute(DelegateExecution execution) throws Exception {
execution.getProcessEngineServices()
.getRuntimeService()
.createMessageCorrelation("someMessage")
.processInstanceBusinessKey("someBusinessKey")
.correlate();
}
}
But I am getting this error::
An error happend while submitting the task form : Cannot submit task form c0e85bad-719f-11e5-94aa-d897baecf24a: Cannot correlate message someMessage: No process definition or execution matches the parameters
How can I debug it?
The error message says, that your JavaDelegate code just gets excuted correctly. The process engine tries to find a running process instance with 'someBusinessKey' as business key and currently waiting for a message 'someMessage', but does not find such an instance. Your code acts as if there were such an instance and you try to find it and tell it about a message. See the docs section about correlation methods - in principle the mechanism is used to 'route' a message to the correct instance targeting it.
As a sidenote: your JavaDelegate seems to get called in the same transaction with which you also try to complete a task. The "borders of transactions" in your process can be managed with 'async' attributes described in the docs section about transactions in processes.

Waiting for EC2 instance to launch and be in running state

I am writing a program using AWS Java SDK to create EC2 instances and do some processing once they are launched.
I have written the following code but I know there could be a better way to do this:
public static void main(String[] args) {
// Some code initialization here
Instance ec2instance;
do {
try {
Thread.sleep(sleep_cyle);
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
} while(ec2instance.getState().getCode() != 16);
//Proceed with processing after instance is running
}
Thank you.
Since there is nothing reporting back to your application related to status changes, the only way to identify changes is to poll every 15-30 seconds.
There are rare cases where an instance may simply fail to launch. Your code should expect the possibility of going from pending to terminated.