I'm using Trial Ultimate version of PostSharp 4.0 but this doesn't work for me. Can you please check my code and advise. The error doesn't gets logged. And if i put the breakpoint doesn't hit onException method
This is code that I've written for Error handling Aspect
[Serializable]
public class MyMethodAspectAttribute : OnMethodBoundaryAspect
{
public MyMethodAspectAttribute()
{
this.ApplyToStateMachine = true;
}
public override void OnEntry(MethodExecutionArgs args)
{
Console.Write("Method Entry");
}
public override void OnException(MethodExecutionArgs args)
{
Console.Write(args.Exception.Message);
args.ReturnValue = null;
args.FlowBehavior = FlowBehavior.Return;
}
}
This is class where I've implemented this aspect
public class ErrorMethods
{
[MyMethodAspect]
public Task<int> Calculate(int i, int j)
{
var task = Task.Factory.StartNew(
() => i / j);
return task;
}
}
This is how I've used this method
private async void Button_Click(object sender, RoutedEventArgs e)
{
var obj = new ErrorMethods();
var result = await obj.Calculate(1, 0);
if (null == result)
{
MessageBox.Show("error");
}
}
The Calculate method in your example is not an async method, so setting ApplyToStateMachine aspect's property doesn't have effect on this method. The exception is thrown when a newly created task executes in the background and the aspect has no chance of catching it.
If you change your Calculate method to async method, then the async state machine execution can be intercepted by the aspect and OnException handler is invoked upon exception.
Note, however that setting the ReturnValue and FlowBehavior does not alter the flow of the state machine, so the exception will not be swallowed.
public class ErrorMethods
{
[MyMethodAspect]
public async Task<int> Calculate( int i, int j )
{
return await Task.Factory.StartNew( () => i / j );
}
}
Related
The accelerometer is activated (if I set ReadingChanged it works).
Why the shaking event isn't handled?
namespace AppExample
{
public sealed partial class MainPage : Page
{
private Accelerometer accel;
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
accel = Accelerometer.GetDefault();
//accel.ReadingChanged += accel_ReadingChanged;
accel.Shaken += accel_Shaken;
}
void accel_Shaken(Accelerometer sender, AccelerometerShakenEventArgs args)
{
Debug.WriteLine("shaken");
}
}
}
If you mind, there is helper librairy called ShakeGestures to handle shake gestures for windows phone 8. check this question
If you're running Windows Phone 8 , Shaken event won't trigger and does not raise any errors according to MSDN page.
Otherwise it seems like a weird bug to me , I couldn't find any information about it.
You can call the Dispatcher in order to show the result on the main thread.
namespace AppExample
{
public sealed partial class MainPage : Page
{
Accelerometer accel;
public MainPage()
{
this.InitializeComponent();
accel = Accelerometer.GetDefault();
accel.ReadingChanged += accel_ReadingChanged;
accel.Shaken += accel_Shaken;
}
await this.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
LabelTest.Text = "Shaken!! " + args.Reading.AccelerationX.ToString();
});
async private void accel_Shaken(object sender, AccelerometerShakenEventArgs e)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
_shakeCount++;
ScenarioOutputText.Text = _shakeCount.ToString();
});
}
}
}
I've made a script that take some public object reference.
But depending on which function i call, one reference is fine but in the other function it's null, i don't understand why.
In the function onSave(), the reference to database is fine and i can access her function like add.
Then, when i call the function edit (which is supposed to retrieve an object into database and fill the form with data) the reference to database is null.
Error log (line 33 is this one: Step step = this.database.get(this.scrollList.selectedItem);:
> NullReferenceException: Object reference not set to an instance of an object
StepForm.edit () (at Assets/Prefabs/Scripts/StepForm.cs:33)
UnityEngine.Events.InvokableCall.Invoke (System.Object[] args) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:110)
UnityEngine.Events.InvokableCallList.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:574)
UnityEngine.Events.UnityEventBase.Invoke (System.Object[] parameters) (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:716)
UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:53)
UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:35)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:44)
UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:52)
UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:269)
UnityEngine.EventSystems.EventSystem:Update()
here is my script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class StepForm : MonoBehaviour {
public Database database;
public ScrollList scrollList;
public InputField title;
public InputField content;
private string uid;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void onSave(){
Step newStep = new Step (this.title.text, this.content.text);
this.database.addStep (newStep);
}
public void onCancel(){
Debug.Log ("onCancel");
}
public void onDelete(){
Debug.Log ("onDelete");
}
public void edit(){
Step step = this.database.get(this.scrollList.selectedItem);
if (step != null) {
this.title.text = step.Title;
this.content.text = step.Content;
}
}
}
The script reference source:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Database : MonoBehaviour {
// Update is called once per frame
void Update () {
}
private List<Step> steps = new List<Step>();
// Use this for initialization
void Start () {
}
public List<Step> Steps {
get {
return this.steps;
}
}
public void addStep(Step newStep)
{
//if (!this.exist(newStep.Uid))
this.steps.Add(newStep);
}
public void deleteStep (Step newStep)
{
this.steps.Remove(newStep);
}
public void updateStep(string uid, Step newStep)
{
Step step = this.Steps.Find(o => o.Title == newStep.Title);
if (step != null) {
step.Title = newStep.Title;
step.Content = newStep.Content;
}
}
private bool exist(string uid)
{
if (this.Steps.Find (o => o.Uid == uid) != null)
return (true);
return (false);
}
public Step get(string uid)
{
Step step = this.Steps.Find (o => o.Uid == uid);
Debug.Log ("GET DATABASE");
Debug.Log (step.Title);
return (step);
}
public void debugContent(){
foreach (Step step in this.steps) {
Debug.Log ("### Debug Step ###");
Debug.Log(step.Uid);
Debug.Log(step.Title);
Debug.Log(step.Content);
}
}
public void clearDatabase(){
this.steps.Clear ();
Debug.Log ("Database cleared!");
}
}
This question is very useful. There're some questions about calling multiple AsyncCallback but they didn't tell how to call them in a loop.
Here is my problem. I am doing a project using Gwt-platform. I got a presenter TestPresenter.java which has these codes:
#Inject
DispatchAsync dispatchAsync;
private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(GetDataResult result) {
// do Something o show the gui here
}
};
public void load_All_Gui_At_Once() {
for(int i=0; i<5; i++) {
GetData getDataAction=new GetData(i);
dispatchAsync.execute(getDataAction, getDataCallback);
}
}
The problem is that the program show the data but it showed in the wrong order. This is cos the next Async method started to run while the previous one has not finish yet.
Some suggested me to put the 2nd call inside onSuccess, but that is only for simple 2 sync calls. But in my case, I have to loop many unknown number of Async calls, then how can i do it?
This is a question similar to this one. All your calls are executed in the same instant, but the response time is unknown and it is not guaranteed the order. So the solution is almost the same, call the loop inside the callback. Your code should look like:
#Inject
DispatchAsync dispatchAsync;
private AsyncCallback<GetDataResult> getDataCallback = new AsyncCallback<GetDataResult>() {
int idx = 0;
#Override
public void onFailure(Throwable caught) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(GetDataResult result) {
if (result != null) {
// do Something or show the gui here
}
if (idx < 5) {
GetData getDataAction = new GetData(idx);
dispatchAsync.execute(getDataAction, getDataCallback);
}
idx ++;
}
};
public void load_All_Gui_At_Once(){
// Start the loop, calling onSuccess the first time
getDataCallback.onSuccess(null);
}
I'm trying to create an IObservable from the following event:
public delegate bool Handle<in T>(T obj, Foo foo);
event Handle<Bar> Finance;
Any suggestions on how to properly create the observable?
Note, neither Foo nor Bar is based on EventArgs
Thanks!
You can try something like:
public class Test
{
public delegate void Handle<in T>(T obj, Foo foo);
public event Handle<Bar> Finance;
}
public static class TestEx
{
static IObservable<Tuple<Bar, Foo>> WhenFinanceChanged(this Test t)
{
return Observable.Create<Tuple<Bar, Foo>>(observer =>
{
Test.Handle<Bar> handler = (obj, foo) => observer.OnNext(Tuple.Create<Bar, Foo>(obj, foo));
t.Finance += handler;
return Disposable.Create(() => t.Finance -= handler);
});
}
}
I'm considering re-rewriting some of my MVC controllers to be async controllers. I have working unit tests for these controllers, but I'm trying to understand how to maintain them in an async controller environment.
For example, currently I have an action like this:
public ContentResult Transaction()
{
do stuff...
return Content("result");
}
and my unit test basically looks like:
var result = controller.Transaction();
Assert.AreEqual("result", result.Content);
Ok, that's easy enough.
But when your controller changes to look like this:
public void TransactionAsync()
{
do stuff...
AsyncManager.Parameters["result"] = "result";
}
public ContentResult TransactionCompleted(string result)
{
return Content(result);
}
How do you suppose your unit tests should be built? You can of course invoke the async initiator method in your test method, but how do you get at the return value?
I haven't seen anything about this on Google...
Thanks for any ideas.
As with any async code, unit testing needs to be aware of thread signalling. .NET includes a type called AutoResetEvent which can block the test thread until an async operation has been completed:
public class MyAsyncController : Controller
{
public void TransactionAsync()
{
AsyncManager.Parameters["result"] = "result";
}
public ContentResult TransactionCompleted(string result)
{
return Content(result);
}
}
[TestFixture]
public class MyAsyncControllerTests
{
#region Fields
private AutoResetEvent trigger;
private MyAsyncController controller;
#endregion
#region Tests
[Test]
public void TestTransactionAsync()
{
controller = new MyAsyncController();
trigger = new AutoResetEvent(false);
// When the async manager has finished processing an async operation, trigger our AutoResetEvent to proceed.
controller.AsyncManager.Finished += (sender, ev) => trigger.Set();
controller.TransactionAsync();
trigger.WaitOne()
// Continue with asserts
}
#endregion
}
Hope that helps :)
I've written short AsyncController extension method that simplifies unit testing a bit.
static class AsyncControllerExtensions
{
public static void ExecuteAsync(this AsyncController asyncController, Action actionAsync, Action actionCompleted)
{
var trigger = new AutoResetEvent(false);
asyncController.AsyncManager.Finished += (sender, ev) =>
{
actionCompleted();
trigger.Set();
};
actionAsync();
trigger.WaitOne();
}
}
That way we can simply hide threading 'noise':
public class SampleAsyncController : AsyncController
{
public void SquareOfAsync(int number)
{
AsyncManager.OutstandingOperations.Increment();
// here goes asynchronous operation
new Thread(() =>
{
Thread.Sleep(100);
// do some async long operation like ...
// calculate square number
AsyncManager.Parameters["result"] = number * number;
// decrementing OutstandingOperations to value 0
// will execute Finished EventHandler on AsyncManager
AsyncManager.OutstandingOperations.Decrement();
}).Start();
}
public JsonResult SquareOfCompleted(int result)
{
return Json(result);
}
}
[TestFixture]
public class SampleAsyncControllerTests
{
[Test]
public void When_calling_square_of_it_should_return_square_number_of_input()
{
var controller = new SampleAsyncController();
var result = new JsonResult();
const int number = 5;
controller.ExecuteAsync(() => controller.SquareOfAsync(number),
() => result = controller.SquareOfCompleted((int)controller.AsyncManager.Parameters["result"]));
Assert.AreEqual((int)(result.Data), number * number);
}
}
If you want to know more I've written a blog post about how to Unit test ASP.NET MVC 3 asynchronous controllers using Machine.Specifications
Or if you want to check this code it's on a github