WF 4 OnUnhandledException not hit - workflow-foundation-4

I've created a custom activity which contains as a Body another Activity.
[Browsable(false)]
public Activity Body { get; set; }
protected override void Execute(NativeActivityContext context)
{
ActivityInstance res = context.ScheduleActivity(Body, new CompletionCallback(OnExecuteComplete), OnFaulted);
}
private void OnFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom)
{
throw new Exception(propagatedException.Message);
}
When an exception is thrown during the execution of the Body, ma handler for the OnFaulted is hit.
My execution starts with a call to static method Run of the WorkflowApplication class. My WorkflowApplication instance has a handler associated for the OnUnhandledException event.
instance.OnUnhandledException +=
delegate(WorkflowApplicationUnhandledExceptionEventArgs args)
{
Console.WriteLine(args.ExceptionSource);
waitEvent.Set();
return UnhandledExceptionAction.Cancel;
};
But regardless of what happens when the Activity hosted in the Body is executed, i never reach the handler defined above. I thought that if i throw an exception from the OnFaulted, i will be able to redirect the flow to the OnUnhandledException but i was wrong. Any ideas ?
I need this in order to centralize my errors, check them and display messages accordingly. Also i need a way to stop the execution and so on and i don't want to define handlers all over the application. Is there any way to accomplish this ?

As Will suggested, i will post what i did to handle my scenario.
Basically, in my custom activity i have hosted an Assign :
[Browsable(false)]
public Activity Body { get; set; }
Activity System.Activities.Presentation.IActivityTemplateFactory.Create(System.Windows.DependencyObject target)
{
return new Assignment()
{
Body = new Assign() { DisplayName = "" }
};
}
I've added this code to my Execute method :
ActivityInstance res = context.ScheduleActivity(Body, new CompletionCallback(OnExecuteComplete), OnFaulted);
I was trying to run this Assignment by giving an array a negative value as index and and an exception was thrown. This, somehow ended my execution but no handler for the events of my WorkflowApplication instance were hit.
Here is the method given as a callback when executing the body ( in our case the Assign activity ) :
private void OnFaulted(NativeActivityFaultContext faultContext, Exception propagatedException, ActivityInstance propagatedFrom)
{
faultContext.HandleFault();
CommunicationExtension ce = faultContext.GetExtension<CommunicationExtension>();
ITextExpression toTextExpression = (propagatedFrom.Activity as Assign).To.Expression as ITextExpression;
string valueTextExpression = string.Empty;
if ((propagatedFrom.Activity as Assign).Value != null)
{
if ((propagatedFrom.Activity as Assign).Value.Expression != null)
valueTextExpression = (propagatedFrom.Activity as Assign).Value.Expression.ToString();
}
if (ce != null)
{
ce.AddData(string.Format("{0} found on Assignment definition [{1} = {2}]", propagatedException.Message, toTextExpression.ExpressionText, valueTextExpression));
}
}
The trick was to call :
faultContext.HandleFault();
and use CommunicationExtension to allow me to to display the erros in the GUI.
The code for this class is trivial :
public class CommunicationExtension
{
public List<string> Messages { get; set; }
public CommunicationExtension()
{
Messages = new List<string>();
}
public void AddData(string message)
{
if (string.IsNullOrEmpty(message))
return;
Messages.Add(message);
}
}
Use this to add the extension:
CommunicationExtension ce = new CommunicationExtension();
instance.Extensions.Add(ce);
where instance is my WorkflowApplication instance.
I understood that for each instance of the workflow application we have one instance of its extension class. So i can send messages like this from all my custom activities in order to display their status.
I hope this scenario can help other people too.

Related

Application Insights Telemetry filtering is not working

I have already followed the guide here. I have tried both the config and "in code" approach of initializing and registering our telemetry processor. My goal is to filter out some HTTP responses so that those don't make their way to the sampled data. I haven't had any success. While our processor is initialized on app start, the Process method is never hit. Also, I already made sure that there is an InstrumentationKey in the config and that I'm using the correct key. What else am I missing?
This is what I have:
public class MyTelemetryProcessor : ITelemetryProcessor
{
private ITelemetryProcessor Next { get; set; }
// You can pass values from .config
public string MyParamFromConfigFile { get; set; }
// Link processors to each other in a chain.
public MyTelemetryProcessor(ITelemetryProcessor next)
{
this.Next = next; <-- this is always hit indicating this processor is active
}
public void Process(ITelemetry item)
{
// To filter out an item, just return
if (!OKtoSend(item)) { return; } <-- breakpoint here is never hit
// Modify the item if required
ModifyItem(item);
this.Next.Process(item);
}
private bool OKtoSend(ITelemetry item) <-- and consequently this method is never hit
{
var request = item as RequestTelemetry; <-- breakpoint here is never hit
// some more code goes here
return request.Success.GetValueOrDefault(false);
}
// Example: replace with your own modifiers.
private void ModifyItem(ITelemetry item)
{
item.Context.Properties.Add("app-version", "1." + MyParamFromConfigFile);
}
}
And this is how it is registered. I can see this being hit during debugging when the app starts up:
var builder = TelemetryConfiguration.Active.TelemetryProcessorChainBuilder;
builder.Use((next) => new MyTelemetryProcessor (next));
builder.Build();
In aspnetcore, my solution was to use :
services.AddApplicationInsightsTelemetryProcessor(typeof(BasicTelemetryFilter));
(using the regular CreateWebHostBuilder :
WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>();
)

Set up an actitivity that will blocked until a new element insert into my database

I'm new in workflows C #, I want to set up an activity that will be blocked until a new element insert into my database , after I pass to another activity.
From your question I believe you are asking for a way to stop the workflow proceeding until you get a database entry and if you do to continue the workflow.
And if you do not get the entry to not continue the workflow.
This answer uses the Flowchart model of workflows.
A way to do this is to write an Code Activity (also called Custom Activity) that reads your database and determines if the entry has arrived and then sets a bool Out Argument of the activity. This bool should set a Variable in the workflow.
Then after that you add a FlowDecision activity to read the bool Variable.
If true you continue the workflow
If false you add a loop back to your database reading activity.
This solution leaves the workflow running in memory.
There are more sophisticated solutions but as you are new to workflows I have given the most simple.
public sealed class Controller: CodeActivity
{
public OutArgument<String> Item { get; set; }
CodeActivityContext con;
public SqlTableDependency<VacationRequest> _dependency;
private void _dependency_OnChanged(object sender, TableDependency.EventArgs.RecordChangedEventArgs<VacationRequest> even)
{
if (even.ChangeType != ChangeType.None)
{
switch (even.ChangeType)
{
case ChangeType.Update:
try
{
Item.Set(con, "yeééés");// ****Exception
Console.WriteLine("iiiiiiiiiiiiiiii");
//_dependency.Stop();
break;
}
catch (Exception)
{
con.SetValue(Item, "tttt");
break;
}
}
}
}
protected override void Execute(CodeActivityContext context)
{
con = context;
_dependency = new SqlTableDependency<VacationRequest>(ConfigurationManager.ConnectionStrings["DbContext"].ConnectionString, "VacationRequests");
_dependency.OnChanged += _dependency_OnChanged;
_dependency.Start();
//context.SetValue(Item, "test");
}
}

How do I centralize code shared by multiple Web API controllers?

I have close to 10 controllers that currently share the same code. The code is pretty simple, it just checks if a set of data is null and checks if the current user has permission to access the data.
If there is an issue, I throw an HttpResponseException.
The code works when it is sitting in each controller. I have also managed to centralize the code but I think the way I have done it is wrong. I've created a new class which inherits ApiController and then I have the controllers inheriting my new class. This is the only way I could get the HttpResponseExceptions working. Code is as follows:
//New centralized class:
public class AuthorizationClass : ApiController
{
private DataModel db = new DataModel();
public async Task checkUserisValid(int user_id)
{
user_list user_list = await db.user_list.FindAsync(user_id);
if (user_list == null)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
}
int businessID = user_list.business_id;
var result = checkAccess(User.Identity.Name, businessID);
if (result.Count <= 0)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
}
}
public static List<user_details> checkAccess(string userName, int id)
{
//code which checks if the user is in the right tables
return checkAccess.ToList();
}
}
Then in the controller class, I have:
public class MyController : AuthorizationClass
{
public async Task<IHttpActionResult> Postnew_table(int id, new_table new_table)
{
await checkUserisValid(id);
//rest of controller
}
}
I tried to do it in different ways but this is the only way I could get it working with HttpResponseException. Is there a better way to do this without inheriting classes or is this the only way to do what I am after?
Thanks.
You could just move these 2 methods to some static helper class in a common assembly, you mention that Request is an instance variable on the controller, just pass it to the method.
public static class SomeHelper
{
public static async Task checkUserisValid(int user_id, DataModel db, Request request, User user)
{
user_list user_list = await db.user_list.FindAsync(user_id);
if (user_list == null)
{
throw new HttpResponseException(request.CreateErrorResponse(HttpStatusCode.BadRequest,"This user does not exist"));
}
int businessID = user_list.business_id;
var result = checkAccess(user.Identity.Name, businessID);
if (result.Count <= 0)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You do not have access to modify this business"));
}
}
public static List<user_details> checkAccess(string userName, int id)
{
//code which checks if the user is in the right tables
return checkAccess.ToList();
}
}

Synchronous responses to `Gdx.net.sendHttpRequest` in LibGDX

I'm making a small game in LibGDX. I'm saving the player's username locally as well as on a server. The problem is that the application is not waiting for the result of the call so the online database's ID is not saved locally. Here's the overall flow of the code:
//Create a new user object
User user = new User(name);
//Store the user in the online database
NetworkService networkService = new NetworkService();
String id = networkService.saveUser(user);
//Set the newly generated dbase ID on the local object
user.setId(id);
//Store the user locally
game.getUserService().persist(user);
in this code, the id variable is not getting set because the saveUser function is returning immediately. How can I make the application wait for the result of the network request so I can work with results from the server communication?
This is the code for saveUser:
public String saveUser(User user) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("action", "save_user");
parameters.put("json", user.toJSON());
HttpRequest httpGet = new HttpRequest(HttpMethods.POST);
httpGet.setUrl("http://localhost:8080/provisioner");
httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters));
WerewolfsResponseListener responseListener = new WerewolfsResponseListener();
Gdx.net.sendHttpRequest (httpGet, responseListener);
return responseListener.getLastResponse();
}
This is the WerewolfsResponseListener class:
class WerewolfsResponseListener implements HttpResponseListener {
private String lastResponse = "";
public void handleHttpResponse(HttpResponse httpResponse) {
System.out.println(httpResponse.getResultAsString());
this.lastResponse = httpResponse.getResultAsString();
}
public void failed(Throwable t) {
System.out.println("Saving user failed: "+t.getMessage());
this.lastResponse = null;
}
public String getLastResponse() {
return lastResponse;
}
}
The asynchrony you are seeing is from Gdx.net.sendHttpRequest. The methods on the second parameter (your WerewolfsResponseListener) will be invoked whenever the request comes back. The success/failure methods will not be invoked "inline".
There are two basic approaches for dealing with callbacks structured like this: "polling" or "events".
With polling, your main game loop could "check" the responseListener to see if its succeeded or failed. (You would need to modify your current listener a bit to disambiguate the success case and the empty string.) Once you see a valid response, you can then do the user.setId() and such.
With "events" then you can just put the user.setId() call inside the responseListener callback, so it will be executed whenever the network responds. This is a bit more of a natural fit to the Libgdx net API. (It does mean your response listener will need a reference to the user object.)
It is not possible to "wait" inline for the network call to return. The Libgdx network API (correctly) assumes you do not want to block indefinitely in your render thread, so its not structured for that (the listener will be queued up as a Runnable, so the earliest it can run is on the next render call).
I would not recommend this to any human being, but if you need to test something in a quick and dirty fashion and absolutely must block, this will work. There's no timeout, so again, be prepared for absolute filth:
long wait = 10;
while(!listener.isDone())
{
Gdx.app.log("Net", "Waiting for response");
try
{
Thread.sleep(wait *= 2);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static class BlockingResponseListener implements HttpResponseListener
{
private String data;
private boolean done = false;
private boolean succeeded = false;
#Override
public void handleHttpResponse(HttpResponse httpResponse)
{
Gdx.app.log("Net", "response code was "+httpResponse.getStatus().getStatusCode());
data = httpResponse.getResultAsString();
succeeded = true;
done = true;
}
#Override
public void failed(Throwable t)
{
done = true;
succeeded = false;
Gdx.app.log("Net", "Failed due to exception ["+t.getMessage()+"]");
}
public boolean succeeded()
{
return succeeded;
}
public boolean isDone()
{
return done;
}
public String getData()
{
return data;
}
}

How to automatically call a method when Session["something"] throws a NullReferenceException?

I am going to be using Session["firmaid"] quite alot in my application. This value is set when someone logs in to my system.
If something happens, and this value is lost from the Session, i would like to somehow have a global method that will get it, if it throws a NullReferenceException.
How can i do this?
Currently, my solution is to try and catch every time i use Session["firmaid"], then execute the method that will put firmaid in the Session, if it throws an Exception.
Is there an easier way to do this?
Instead of try/catching everytime you could wrap the access to the session in a strongly typed class and then access the session through this wrapper.
Or even write an extension method:
public static class SessionExtensions
{
public static string GetFirmaId(this HttpSessionStateBase session)
{
var firmaid = session["firmaid"] as string;
if (string.IsNullOrEmpty(firmaid))
{
// TODO: call some method, take respective actions
}
return firmaid;
}
}
and then in your code instead of:
try
{
var firmaid = Session["firmaid"];
// TODO: do something with the result
}
catch (Exception ex)
{
// TODO: call some method, take respective actions
}
use:
var firmaid = Session.GetFirmaId();
// TODO: do something with the result
Why not simply write a static wrapper around this? Much more robust and more DRY:
public static int GetFirmaid() {
if (HttpContext.Current.Session["firmaid"] == null) {
//do something to fall back
}
return HttpContext.Current.Session["firmaid"]
}
You obviously would have to put this in a Class you can easily access and then call it through:
Class.GetFirmaid()
You can create an action filter which will ensure that Session["firmaid"] has a value:
public class SetFirmaIdAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
try
{
var firmaId = Session["firmaid"];
}
catch (Exception ex)
{
// pass filterContext if you need access to Request, Session etc.
Session["firmaid"] = SetFirmaId(filterContext);
}
}
private int SetFirmaId(ActionExecutingContext filterContext)
{
// TODO: implement some logic
}
}
OnActionExecuting will be called before action executes so you will already have Session["firmaid"] set when the action gets executed.
Once you implement this attribute you can put it on an action, controller or set it as global.

Resources