How to pass parameters to a method by reflection - events

Further to my precedent question, I want to pass parameters to the method "WriteTrace". But I don't know how to do this.
Here the actual code :
public class Trace
{
public void WriteTrace(object sender, EventArgs e)
{
Console.WriteLine("Trace !");
}
}
public void SubscribeEvent(Control control)
{
if (typeof(Control).IsAssignableFrom(control.GetType()))
{
Trace test = this;
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
EventInfo eventInfo = control.GetType().GetEvent("Load");
// Create the delegate on the test class because that's where the
// method is. This corresponds with `new EventHandler(test.WriteTrace)`.
Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, test, method);
// Assign the eventhandler. This corresponds with `control.Load += ...`.
eventInfo.AddEventHandler(control, handler);
}
}
Now I want to get some infos in the trace :
The name of the control
The name of the event
public void WriteTrace(object sender, EventArgs e)
{
Console.WriteLine("Control : " + e.ControlName + "Event : " + e.EventName);
}
Do I create a class TraceEventArgs which derives from EventArgs with these infos ?
How to pass these infos in the method SubscribeEvent ?
Thanks for your help,
Florian
EDIT
Sorry, here now the reference to "my previous question" : Subscribe to an event with Reflection

Try something like this:
public void WriteTrace(object sender, EventArgs e, string eventName)
{
Control c = (Control)sender;
Console.WriteLine("Control: " + f.Name + ", Event: " + eventName);
}
public void SubscribeEvent(Control control, string eventName) {
EventInfo eInfo = control.GetType().GetEvent(eventName);
if (eInfo != null) {
// create a dummy, using a closure to capture the eventName parameter
// this is to make use of the C# closure mechanism
EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eventName);
// Delegate.Method returns the MethodInfo for the delegated method
Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
eInfo.AddEventHandler(control, realDelegate);
}
}

Related

Getting data from the observable collection to the button event

public ObservableCollection<WordList> MyWordList { get; set; }
public DictionaryPage()
{
InitializeComponent();
BindingContext = new DictionaryPageViewModel();
MyWordList = new ObservableCollection<WordList>
{
new WordList { Color = "Red", Letter = "A", Word = "Abdomen", Meaning = "Mean : " + "Mean",Detail= "Mean", Voice = "myVoice.mp3" }
};
}
private async void PronunciationButton_Clicked(object sender, System.EventArgs e)
{
await CrossMediaManager.Current.PlayFromAssembly("HERE HERE HERE");
}
I have an observable collection like this and I want to put the voice value in it to the button event below. Thanks for your help
MyWordList is a class level variable. Just reference it in your Clicked handler
private async void PronunciationButton_Clicked(object sender, System.EventArgs e)
{
For each (var word in MyWordList) {
await CrossMediaManager.Current.PlayFromAssembly(word.Voice);
}
}

Method as Event Handler

can anyone help with my problem ?
I have 2 classes.
public partial class StationTabItem : UserControl
{
SessionServiceClass.Instance.getHistoricalStationData(Convert.ToUInt32(station.stationNumber), setHistoricalStationData);
public void setHistoricalStationData(object sender, readStationDataHistoryCompletedEventArgs e)
{
if (!e.Cancelled && (e.Error == null))
{
historicalStationData = new List<StationData>();
historicalStationData = e.Result.ToList();
fillHistoricalData(historicalStationData);
InitializeComponent();
ComboBox_Left.SelectedIndex = leftIndex;
ComboBox_Right.SelectedIndex = rightIndex;
TextBlock_StationName.Text = stationName;
TextBox_DetailsInfo.Text = evidUdajeStanice;
fillStationData(station);
updateDataGrids(localDynamicData_weatherData.variables, localDynamicData_alignedSurfaceData.variables, localDynamicData_oppositeSurfaceData.variables);
}
}
and second class
public class SessionServiceClass
{
public void getHistoricalStationData(uint stationID, EventHandler<readStationDataHistoryCompletedEventArgs> setHistoricalStationData)
{
rwisClient.readStationDataHistoryAsync(stationID, System.DateTime.Today.AddHours(System.DateTime.Now.Hour).AddMinutes(System.DateTime.Now.Minute), -86400);
rwisClient.readStationDataHistoryCompleted -= setHistoricalStationData;
rwisClient.readStationDataHistoryCompleted += setHistoricalStationData;
}
}
The problem is, if I create more instances of StationTabItem, allways is called every method setHistricalStationData in every instance but with result ,,e.result,, of last istances. It means my variable historicalStationData is overwrite as is last value of it.
Thanks in advance for any ideas.

how to declare and use the event handler for dynamically created array of textboxes in wp7 using C#?

I'm new to windows phone 7. I had created a array of textboxes dynamically. And I don't know where and how to declare and use the event handler for the textboxes. My code is shown below:
public partial class MainPage : PhoneApplicationPage
{
public TextBox[] textbox;
public MainPage()
{
InitializeComponent();
string[] str = new string[2];
str[0] = "force";
str[1] = "force components";
textbox = new TextBox[2];
for (int i = 0; i < 2; i++)
{
textbox[i] = new TextBox { Text = str[i] };
textbox[i].Tap += new System.EventHandler(this.textbox[i]_Tap);
listBox1.Items.Add (textbox[i]);
}
}
private void textbox[0]_Tap(object sender, RoutedEventArgs e)
{
}
private void textbox[1]_Tap(object sender, RoutedEventArgs e)
{
}
}
The above code shows error, while declaring and using the event handler method. please help me with a understandable piece of code, to clear my errors. Thank You for All.
You cannot name a Method "private void textbox[1]_Tap" the [] is the thing which is not allowed. So even if you would name it: "private void textbox1_Tap", you wouldnt be able to call the function when you put an 'i' into it.
Thats because the Name of the Function is Reference and the Compiler later will not remember the Names of variables, functions, etc..

Where to access the isolated storage value?

public IsolatedStorageSettings appSettings =
IsolatedStorageSettings.ApplicationSettings;
public Settings()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
this.toggle.Click += new EventHandler<RoutedEventArgs>(toggle_Click);
this.toggle.Indeterminate += new EventHandler<RoutedEventArgs>(toggle_Indeterminate);
`}`
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Visibity is off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
appSettings.Add("value", "off");
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Visibity is on";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
appSettings.Add("value", "on");
}
void toggle_Indeterminate(object sender, RoutedEventArgs e)
{
//add some content here
}
void toggle_Click(object sender, RoutedEventArgs e)
{
//add some content here
}
by default calling checked method.If a user unchcked the button then again an user logged in app need to show the unchcked because the user previously unchcked the btn.but it's show checked.for that i am saving one value in isolated storage.
can you please tell me where to access the isolated varieable value ?
You can access the isolatedstorage value in any page, in the same way as you created it.
Try to access the value in Settings() constructor after the InitializeComponent();
public Settings()
{
InitializeComponent();
string value;
if (appSettings.Contains("value"))
{
appSettings.TryGetValue("value", out value);
}
and then you can change the value of toggle button based on the 'value'.
It seems that you are not calling the Save method on the ApplicationSettings object.
Please read this guide on how you should work with isolated storage.
To save a setting:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (!settings.Contains("userData"))
{
settings.Add("userData", "some value");
}
else
{
settings["userData"] = "some value";
}
settings.Save();
To retrieve a setting:
if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))
{
string result IsolatedStorageSettings.ApplicationSettings["userData"] as string;
}
So in your case, save the state of the CheckBox in the Checked & UnChecked event, and load the state in the init of the page.

What is the TPL equivalent of rx's Observable.FromEventPattern?

In rx you can write :
var oe = Observable.FromEventPattern<SqlNotificationEventArgs>(sqlDep, "OnChange");
and then subscribe to the observable to convert the OnChange event on the sqlDep object into an observable.
Similarily, how can you create a Task from a C# event using the Task Parallel Library ?
EDIT: clarification
The solution pointed by Drew and then written explicitely by user375487 works for a single event. As soon as the task finished ... well it is finished.
The observable event is able to trigger again at any time. It is can be seen as an observable stream. A kind of ISourceBlock in the TPL Dataflow. But in the doc http://msdn.microsoft.com/en-us/library/hh228603(v=vs.110).aspx there is no example of ISourceBlock.
I eventually found a forum post explaining how to do that: http://social.msdn.microsoft.com/Forums/en/tpldataflow/thread/a10c4cb6-868e-41c5-b8cf-d122b514db0e
public static ISourceBlock CreateSourceBlock(
Action,Action,Action,ISourceBlock> executor)
{
var bb = new BufferBlock();
executor(t => bb.Post(t), () => bb.Complete(), e => bb.Fault(e), bb);
return bb;
}
//Remark the async delegate which defers the subscription to the hot source.
var sourceBlock = CreateSourceBlock<SomeArgs>(async (post, complete, fault, bb) =>
{
var eventHandlerToSource = (s,args) => post(args);
publisher.OnEvent += eventHandlerToSource;
bb.Complete.ContinueWith(_ => publisher.OnEvent -= eventHandlerToSource);
});
I've not tryed the above code. There may be a mismatch between the async delegate and the definition of CreateSourceBlock.
There is no direct equivalent for the Event Asynchronous Pattern (EAP) baked into the TPL. What you need to do is using a TaskCompletionSource<T> that you signal yourself in the event handler. Check out this section on MSDN for an example of what that would look like which uses WebClient::DownloadStringAsync to demonstrate the pattern.
You can use TaskCompletionSource.
public static class TaskFromEvent
{
public static Task<TArgs> Create<TArgs>(object obj, string eventName)
where TArgs : EventArgs
{
var completionSource = new TaskCompletionSource<TArgs>();
EventHandler<TArgs> handler = null;
handler = new EventHandler<TArgs>((sender, args) =>
{
completionSource.SetResult(args);
obj.GetType().GetEvent(eventName).RemoveEventHandler(obj, handler);
});
obj.GetType().GetEvent(eventName).AddEventHandler(obj, handler);
return completionSource.Task;
}
}
Example usage:
public class Publisher
{
public event EventHandler<EventArgs> Event;
public void FireEvent()
{
if (this.Event != null)
Event(this, new EventArgs());
}
}
class Program
{
static void Main(string[] args)
{
Publisher publisher = new Publisher();
var task = TaskFromEvent.Create<EventArgs>(publisher, "Event").ContinueWith(e => Console.WriteLine("The event has fired."));
publisher.FireEvent();
Console.ReadKey();
}
}
EDIT Based on your clarification, here is an example of how to achieve your goal with TPL DataFlow.
public class EventSource
{
public static ISourceBlock<TArgs> Create<TArgs>(object obj, string eventName)
where TArgs : EventArgs
{
BufferBlock<TArgs> buffer = new BufferBlock<TArgs>();
EventHandler<TArgs> handler = null;
handler = new EventHandler<TArgs>((sender, args) =>
{
buffer.Post(args);
});
buffer.Completion.ContinueWith(c =>
{
Console.WriteLine("Unsubscribed from event");
obj.GetType().GetEvent(eventName).RemoveEventHandler(obj, handler);
});
obj.GetType().GetEvent(eventName).AddEventHandler(obj, handler);
return buffer;
}
}
public class Publisher
{
public event EventHandler<EventArgs> Event;
public void FireEvent()
{
if (this.Event != null)
Event(this, new EventArgs());
}
}
class Program
{
static void Main(string[] args)
{
var publisher = new Publisher();
var source = EventSource.Create<EventArgs>(publisher, "Event");
source.LinkTo(new ActionBlock<EventArgs>(e => Console.WriteLine("New event!")));
Console.WriteLine("Type 'q' to exit");
char key = (char)0;
while (true)
{
key = Console.ReadKey().KeyChar;
Console.WriteLine();
if (key == 'q') break;
publisher.FireEvent();
}
source.Complete();
Console.ReadKey();
}
}

Resources