eventhandler delegate - delegates

i'm trying to create a timed event using the following code:
// SET UP A TIMER INTERVAL TO POLL INSTRUMENTS ONCE EVERY SECOND
DispatcherTimer^ timer = ref new DispatcherTimer;
timer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &MainPage::Request_Data);
TimeSpan t;
t.Duration = 1000;
timer->Interval = t;
timer->Start();
I'm getting an error on this bit, specifically the &:
timer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &MainPage::Request_Data);
The error is Invalid delegate initializer -- function does not match the delegate type.
Any ideas?

Ok, so my function I was passing to the EventHandler to be called was missing a few bits.
So I had declared this function as:
void MainPage::Request_Data(){
... stuff
}
which should have been declared as:
void MainPage::Request_Data(Platform::Object^ sender, Platform::Object^ e){
... stuff
}

Related

Parse an actual time to TimePicker

I'm new here so bare a bit with me. And yes i tried to google my question but really wasn't shure about the answers i found either.
So here's my problem:
I want to build an App where the User can select a Times from clicking different Buttons, and then calculate the Timedifference between.
The ButtonClick opens the TimePicker Dialog and the Examplecode i found on Microsoft Docs uses always the actual time. What i want is to use the last valid time from parsing the Buttontext. But i have no idea how to pass the ID of the senderbutton to the TimePicker class.
Here's the Eventhandler from the Button:
void TimeSelectOnClick (object sender, EventArgs eventArgs)
{
// Instantiate a TimePickerFragment (defined below)
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
});
// Launch the TimePicker dialog fragment (defined below):
frag.Show(FragmentManager, TimePickerFragment.TAG);
}
and here's the TimePicker dialog fragment:
// TimePicker dialog fragment
public class TimePickerFragment : DialogFragment, TimePickerDialog.IOnTimeSetListener
{
// TAG used for logging
public static readonly string TAG = "MyTimePickerFragment";
// Initialize handler to an empty delegate to prevent null reference exceptions:
Action<DateTime> timeSelectedHandler = delegate { };
// Factory method used to create a new TimePickerFragment:
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
// Return the new TimePickerFragment:
return frag;
}
// Create and return a TimePickerDemo:
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
//Set the TimePicker default time
//Here i Want to parse the time from the button something like DateTime.Parse(buttonID.Text);
//Either with current time or parsed time... how to pass values from the sender button i have no idea
DateTime currentTime = DateTime.Parse("06:00");
// force 24-hour time format:
bool is24HourFormat = true;
// Instantiate a new TimePickerDemo, passing in the handler, the current
// time to display, and whether or not to use 24 hour format:
TimePickerDialog dialog = new TimePickerDialog
(Activity, this, currentTime.Hour, currentTime.Minute, is24HourFormat);
// Return the created TimePickerDemo:
return dialog;
}
// Called when the user sets the time in the TimePicker:
public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
{
// Get the current time:
DateTime currentTime = DateTime.Now;
// Create a DateTime that contains today's date and the time selected by the user:
DateTime selectedTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, hourOfDay, minute, 0);
// Log the date and selected time:
Log.Debug(TAG, selectedTime.ToLongTimeString());
// Invoke the handler to update the Activity's time display to the selected time:
timeSelectedHandler (selectedTime);
}
}
thanks in advance to anybody here on Stackoverflow! You guys really do a great Job!
Cheers
You could add a property in TimePickerFragment
static string TimeString;
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected,string time)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
TimeString = time;
// Return the new TimePickerFragment:
return frag;
}
in Activity
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
},buttonID.Text);
And you can modify it in any place
TimePickerFragment.TimeString = "xxx";

How can i use VALA delegates in GTK3 button callback?

I'm trying to understand Vala delegates with Gtk3.
I tested callback and lambda with no problem.
I wanna test a delegate callback, here my code :
using Gtk;
delegate void typeDelegate(Button button);
int main (string[] args) {
Gtk.init (ref args);
typeDelegate cb = cbLabelf;
var window = new Window ();
window.title = "First GTK+ Program";
window.border_width = 10;
window.window_position = WindowPosition.CENTER;
window.set_default_size (350, 70);
window.destroy.connect (Gtk.main_quit);
var button = new Button.with_label ("Click me!");
//button.clicked.connect (cb);
//button.clicked+= cb;
button.clicked.connect+=cb;
window.add (button);
window.show_all ();
Gtk.main ();
return 0;
}
void cbLabelf(Button button)
{
button.label = "tank yu";
}
I also red generated C code ( when i use lambda) to understand.
Here the compil error :
GTKsampleDelegate.vala:20.5-20.30: error: Arithmetic operation not supported for types Gtk.Button.clicked.connect' andtypeDelegate'
button.clicked.connect+=cb;
Well,
Seems that you want to get the intrinsic variable that holds the instance that emitted the signal, I find strange that vala doesn't let you use a delegate variable to obtain it via parameter, yet, you can use one of the forms below: using no delegation variable (A) or bypassing the error with a closure (B).
public class FooSignalClass : Object {
/* Gtk Button.clicked signal has the void f(void) signature */
public signal void on_foo ();
public void foo() {
on_foo();
}
}
public delegate void FooSignalFunc (FooSignalClass fooer);
void on_foo_handler (FooSignalClass fooer) {
long fooer_memory_address = (long)fooer;
GLib.message(#"fooer exists? $(fooer!=null).");
GLib.message(#"address=$fooer_memory_address.");
}
int main () {
var foo_signal = new FooSignalClass();
long fooer_memory_address = (long)foo_signal;
GLib.message(#"foo_signal address=$fooer_memory_address.");
/* Option A: Connect directly without the delegate variable */
foo_signal.on_foo.connect(on_foo_handler);
/* Option B: You cant use a delegate directly, bypass it with a closure */
FooSignalFunc func = on_foo_handler;
foo_signal.on_foo.connect((instance) => {
func(instance);
});
foo_signal.foo();
return 0;
}

app_message_outbox_send is not in app space

I am working on a Pebble watch face and I ran into a problem, the function app_message_outbox_send seems to throw an error (which then crashes my app). The error is "[INFO ] E call_internal.c:36 syscall failure! 0..0x8 is not in app space."
The relevant code:
static void askPhoneForCharge(){
if(bluetooth_connection_service_peek()){
DictionaryIterator *iter;
app_message_outbox_begin(&iter);
dict_write_uint8(iter, KEY_PHONE_ASK, 0);
app_message_outbox_send();
}else{
phoneCharging = 0;
phoneCharge = 0;
updatePhoneBattery();
}
}
Here is how I set up the handlers and open the channel:
app_message_register_inbox_received(inboxReceivedCallback);
app_message_register_inbox_dropped(inboxDroppedCallback);
app_message_register_outbox_failed(outboxFailedCallback);
app_message_register_outbox_sent(outboxSentCallback);
app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum());
As it turns out, you can not use the message functions while in the initialization phase, so I started a timer that only executes once to take care of the initial messaging.
I was having the same problem while sending the app_message_outbox_send() command which was getting called by to the Up_button_click handler.
The following initialization code in the Init() method fixed it for me.
Look at the "Register message handlers" & "Init buffers"
void out_sent_handler(DictionaryIterator *sent, void *context){}
static void out_fail_handler(DictionaryIterator *failed, AppMessageResult reason, void* context){}
static void in_received_handler(DictionaryIterator *iter, void* context){}
void in_drop_handler(AppMessageResult reason, void *context){}
static void init() {
// Register message handlers
app_message_register_outbox_sent(out_sent_handler);
app_message_register_inbox_received(in_received_handler);
app_message_register_inbox_dropped(in_drop_handler);
app_message_register_outbox_failed(out_fail_handler);
// Init buffers
app_message_open(64, 64);
// Create main Window element and assign to pointer
s_main_window = window_create();
// Set handlers to manage the elements inside the Window
window_set_window_handlers(s_main_window, (WindowHandlers) {
.load = main_window_load,
.unload = main_window_unload
});
// Show the Window on the watch, with animated=true
window_stack_push(s_main_window, true);
}

differences between bound and unbound delegates in CLI/C++

Whats the difference between bound and unbound delegates?
heres how you create delegates of both types:
// bound delegate declaration
public delegate void Handler(int value);
// create a bound delegate
Handler^ handler = gcnew Handler(HandlerClass::Fun1);
// unbound delegate declaration
public delegate void UBHandler(ThisClass^, int value);
// create an unbound delegate
UBHandler^ ubh = gcnew UBHandler(&ThisClass::Sum);
these are nearly the same. then, you can create constructors for bound delegates that consist of two parameters:
HandlerClass^ obj = gcnew HandlerClass;
Handler^ handler2 = gcnew Handler (obj, & HandlerClass::Fun3);
it means that you can use this particular delegate to invoke a function that is not static (is an instance). but then you can do the same with unbound delegates. Here’s how you might call the ubh delegate:
ThisClass^ obj = gcnew ThisClass(99.0);
ubh(obj, 5);
so whats the point of having both types?
// code for HandlerClass
public ref class HandlerClass
{
public:
static void Fun1(int m)
{ Console::WriteLine(L”Function1 called with value {0}”, m); }
static void Fun2(int m)
{ Console::WriteLine(L”Function2 called with value {0}”, m); }
void Fun3(int m)
{ Console::WriteLine(L”Function3 called with value {0}”, m+value); }
void Fun4(int m)
{ Console::WriteLine(L”Function4 called with value {0}”, m+value); }
HandlerClass():value(1){}
HandlerClass(int m):value(m){}
protected:
int value;
};
The difference is the exact time the target object value is generated. With a bound delegate it is generated when you create the delegate object and it is forever unchanging after that. An unbound delegate doesn't store the object reference, it is generated at the time the delegate is invoked. The same delegate can then be used to invoke the target method with different objects.
Unbound delegates are a match with the syntax of C++ member function pointers. There is no direct equivalent for bound delegates in C++.

Proper way of raising events from C++/CLI?

I was wondering what's the proper way of raising events from C++/CLI. In C# one should first make a copy of the handler, check if it's not null, and then call it. Is there a similar practice for C++/CLI?
This isn't the whole story! You don't usually have to worry about null event handlers in C++/CLI. The code for these checks is generated for you. Consider the following trivial C++/CLI class.
public ref class MyClass
{
public:
event System::EventHandler ^ MyEvent;
};
If you compile this class, and disassemble it using Reflector, you get the following c# code.
public class MyClass
{
// Fields
private EventHandler <backing_store>MyEvent;
// Events
public event EventHandler MyEvent
{
[MethodImpl(MethodImplOptions.Synchronized)] add
{
this.<backing_store>MyEvent = (EventHandler) Delegate.Combine(this.<backing_store>MyEvent, value);
}
[MethodImpl(MethodImplOptions.Synchronized)] remove
{
this.<backing_store>MyEvent = (EventHandler) Delegate.Remove(this.<backing_store>MyEvent, value);
}
raise
{
EventHandler <tmp> = null;
<tmp> = this.<backing_store>MyEvent;
if (<tmp> != null)
{
<tmp>(value0, value1);
}
}
}
}
The usual checks are being done in the raise method. Unless you really want custom behavior, you should feel comfortable declaring your event as in the above class, and raising it without fear of a null handler.
C++/CLI allows you to override raise in custom event handlers so you don't have to test for null or copy when raising the event. Of course, inside your custom raise you still have to do this.
Example, adapted from the MSDN for correctness:
public delegate void f(int);
public ref struct E {
f ^ _E;
public:
void handler(int i) {
System::Console::WriteLine(i);
}
E() {
_E = nullptr;
}
event f^ Event {
void add(f ^ d) {
_E += d;
}
void remove(f ^ d) {
_E -= d;
}
void raise(int i) {
f^ tmp = _E;
if (tmp) {
tmp->Invoke(i);
}
}
}
static void Go() {
E^ pE = gcnew E;
pE->Event += gcnew f(pE, &E::handler);
pE->Event(17);
}
};
int main() {
E::Go();
}
If your issue is that raise isn't private, then explicitly implement it like the docs say:
http://msdn.microsoft.com/en-us/library/5f3csfsa.aspx
In summary:
If you just use the event keyword, you create a "trivial" event. The compiler generates add/remove/raise and the delegate member for you. The generated raise function (as the docs say) checks for nullptr. Trivial events are documented here:
http://msdn.microsoft.com/en-us/library/4b612y2s.aspx
If you want "more control", for example to make raise private, then you have to explicitly implement the members as shown in the link. You must explicitly declare a data member for the delegate type. Then you use the event keyword to declare the event-related members, as in the Microsoft example:
// event keyword introduces the scope wherein I'm defining the required methods
// "f" is my delegate type
// "Event" is the unrealistic name of the event itself
event f^ Event
{
// add is public (because the event block is public)
// "_E" is the private delegate data member of type "f"
void add(f ^ d) { _E += d; }
// making remove private
private:
void remove(f ^ d) { _E -= d; }
// making raise protected
protected:
void raise(int i)
{
// check for nullptr
if (_E)
{
_E->Invoke(i);
}
}
}// end event block
Wordy, but there it is.
-reilly.

Resources