method as parameter of function(typedef std::function<void ()>) - class

Hello i try connect the method to parameter TaskCallback of class Task. I don't know how to do this. Could you help me?
typedef std::function<void ()> TaskCallback
class Task {
Task(unsigned long aInterval=0, long aIterations=0, TaskCallback aCallback=NULL, Scheduler* aScheduler=NULL, bool aEnable=false, TaskOnEnable aOnEnable=NULL, TaskOnDisable aOnDisable=NULL
}
class Mesh_PDP : public painlessMesh
}
{
public:
void sendMessage ();
};
Mesh_PDP SensorsMesh;
Task taskSendMessage(TASK_SECOND * 5 , TASK_FOREVER, &(SensorsMesh.sendMessage));// Error
I can create a new function and use it, but I'm not happy with this solution.
void testfunction()
{
SensorsMesh.sendMessage();
}
//Create tasks: to send messages and get readings;
Task taskSendMessage(TASK_SECOND * 5 , TASK_FOREVER, &testfunction);

Related

Is there any counter observable through Rx?

I am looking for something I would call CounterObservable One side would count the numbers on it and other side would be the observer side that will receive notification every time total count changes.
In other words I will have something like this
public CounterObservable totalMailsReceived = new CounterObservable(0);
public void OnNewMail(Mail mail)
{
totalMailsReceived++;
///Rest of the code goes here
}
on the Observer side I will have
mailManager.totalMailsReceived.Subscribe(count => labelCount.Text = count.ToString());
Or if I want to go real classy, I would use Paul Betts' ReactiveUI like the following
mailManager.totalMailsReceived.ToProperty(x => x.TotalMailsReceived);
I have so far found nothing in Rx that could help me. But I figured if I create my own class that implements IObservable<int>. I am thinking of leveraging the Sample MSDN Code for IObservable implementation for that.
My questions are
1. Is that MSDN Sample thread-safe ?
2. Is there really nothing in Rx already that does what I am trying to do ?
Just use a BehaviorSubject:
public class MailServer
{
private BehaviorSubject<int> _count = new BehaviorSubject<int>(0);
public IObservable<int> TotalMailsReceived
{
get { return _count; }
}
public void OnNewMail(Mail mail)
{
_count.OnNext(_count.Value + 1);
}
}
Or, if you decide to go deeper into Rx, so that you are just observing a Mail stream, then you can use Scan operator which is good for that and Publish to remember the most recent value and multicast it to all subscribers.
You can write this new extension method:
public IObservable<T> RunningTotal<T>(this IObservable<T> source)
{
return source.Scan(0, sum => sum + 1);
}
And use it like so:
public class MailServer
{
private IConnectableObservable<int> _total;
private IDisposable _subscription;
public MailServer(IObservable<Mail> incomingMail)
{
_total = incomingMail.RunningTotal().Publish(0);
_subscription = _total.Connect();
}
public IObservable<int> TotalMailsReceived
{
get { return _total; }
}
}

GWT - run command exactly once per event loop

I'm writing some wrapper classes around zurb foundation.
Foundation widgets need an init() function to be called after the elements have been added to the DOM.
I can accomplish this easily enough with this method:
public static void initWidgets() {
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
foundationInit();
}
});
}
...where foundationInit() is a JSNI call to the foundation init() function. I then add a call to initWidgets() in the constructor of any foundation element. So far so good.
However, if multiple foundation widgets are added to the DOM during a particular event loop, then the init() method will be called multiple times. Foundation doesn't actually care about this, but it would be nice to find a way around this.
Is there any scheduler functionality / pattern that'd allow me to schedule a particular command to run only once, no matter how many times the schedule method is called with that command?
Something like: scheduleDeferredIfNotAlreadyScheduled(Command c)
I don't know how to get a handle on the event loop, so I don't know how to reset a flag that'd tell me whether or not to add the command or not.
I don't know any Scheduller command to do that, but it could be done with a static boolean variable, e.g.:
private static boolean initialized;
public static void initWidgets() {
initialized = false;
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
if (!initialized) {
initialized = true;
foundationInit();
}
}
});
}
In such case I usually use Guava's Supplier.double checked locking is really safe.
public static Supplier<Boolean> supplier=Suppliers.memoize(new Supplier<Boolean>() {
#Override
public Boolean get() {
foundationInit();
return true;
}
});
public static void initWidgets() {
Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
#Override
public void execute() {
boolean initialized=supplier.get();
}
});
}

Current InvocationCount in TestNG

I have a method to be tested using TestNG and I have marked it with below annotations:
#Test(invocationCount=10, threadPoolSize=5)
Now, in my test method I would like to get the current invocationCount that is being executed. Is that possible? If yes, then I would be glad to know how.
More proper example:
#Test(invocationCount=10, threadPoolSize=5)
public void testMe() {
System.out.println("Executing count: "+INVOCATIONCOUNT); //INVOCATIONCOUNT is what I am looking for
}
For reference, I am using TestNG plugin in Eclipse.
You can use TestNG dependency injection feature by adding ITestContext parameter in your test method. Please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection.
From the ITestContext parameter, you can call its getAllTestMethods() which returns array of ITestNGMethod. It should returns array of only one element, which refers to the current/actual test method. Finally, you can call getCurrentInvocationCount() of ITestNGMethod.
Your test code should be more-less like the following sample,
#Test(invocationCount=10, threadPoolSize=5)
public void testMe(ITestContext testContext) {
int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
System.out.println("Executing count: " + currentCount);
}
You can get the current invocation count as mentioned below
public class getCurrentInvocationCount {
int count;
#BeforeClass
public void initialize() {
count = 0;
}
#Test(invocationCount = 10)
public void testMe() {
count++;
System.out.println("Current Invocation count "+count)
}
}
I know this is a some kind of stupid way. However it will server your purpose. You can refer testNG source class to get actual current invocationCount
You can use something like this:
public class getCurrentInvocationCount {
AtomicInteger i = new AtomicInteger(0);
#Test(invocationCount = 10, threadPoolSize=5)
public void testMe() {
int count= i.addAndGet(1);
System.out.println("Current Invocation count "+count)
}
}
You can get by calling getCurrentInvocationCount() method of ITestNGMethod
Try to put 2 parameters in #Test method:
java.lang.reflect.Method
Use .getName() to get current method name.
ITestContext
Use .getAllTestMethods() to get all test methods. Then use forEach to extract them by ITestNGMethod and compare with .getName() in point 1.
Finally, use .getCurrentInvocationCount() to achieve this.
#Test(invocationCount=10)
public void testMe(ITestContext context, Method method) {
int invCountNumber = 0;
for(ITestNGMethod iTestMethod: context.getAllTestMethods()) {
if(iTestMethod.getMethodName().equals(method.getName())){
invCountNumber = iTestMethod.getCurrentInvocationCount();
break;
}
}
System.out.println(invCountNumber);
}
Following import:
import java.lang.reflect.Method;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;
When you use invocationCount the test is run like for loop.
I found this to be the easiest way to get the count of test executions.
int count;
#Test(invocationCount = 3)
public void yourTest() {
count++;
System.out.println("test executed count is: " + count)
}

Error with Invoke method in a domainservice class

i'm new with silverlight/ria and i have a problem wath i don't understand.
I have the following code in my domain services class
[EnableClientAccess()]
[KnownType(typeof(ModeleEmailEa))]
[KnownType(typeof(ModeleSmsEa))]
public class EAEMailDomainService : DomainService
{
#region ModeleEnvoiEa CRUD
[Query()]
public IQueryable<ModeleEnvoiEa> SelectAllModeleEnvoiEa()
{
ModeleEnvoiEaSrv modeleService = new ModeleEnvoiEaSrv();
return modeleService.GetList<ModeleEnvoiEa>();
}
[Update]
public void UpdateModeleEnvoiEa(ModeleEnvoiEa modele)
{
ModeleEnvoiEaSrv modeleService = new ModeleEnvoiEaSrv();
modeleService.Update(modele);
}
[Insert]
public void InsertModeleEnvoiEa(ModeleEnvoiEa modele)
{
ModeleEnvoiEaSrv modeleService = new ModeleEnvoiEaSrv();
modeleService.Insert(modele);
}
[Delete]
public void DeleteModeleEnvoiEa(ModeleEnvoiEa modele)
{
ModeleEnvoiEaSrv modeleService = new ModeleEnvoiEaSrv();
modeleService.Delete(modele);
}
[Invoke]
public void Test(int valeur)
{
//Do something
}
#endregion
And this code in my Silverlight application
Context.Test(2, action =>
{
// Do something
}, null);
The function SelectAll, Update, Delete , Insert work's fine but the 'Test' function generated the following error:
an attempt was made to load a program
with an incorrect format
any ideas ?
I have found that if i write the function invocation like this it's works
Context.Test(2,new System.Action<InvokeOperation<Int>>(ModeleEnvoiEa_Completed),null);
}
void ModeleEnvoiEa_Completed(InvokeOperation invoke)
{
// Do something
}
but if i use a lambda expression like this, i have an error, why ?
Context.Test(2, action =>
{
// This code generate an error
// an attempt was made to load a program with an incorrect format
}, null);

Building unit tests for MVC2 AsyncControllers

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