Extract and compare eventargs data - c#

I have a problem comparing data I get from an eventargument, to be more specific, I have 2 classes that uses an interface, lets call it 'IInt'. I also have a list that is filled with objects of these two classes.
I currently use the OnDragDrop event to drag objects from this list, but I need a way to determine if it was an object of class1 or class2 that I draged. Is there a way to extract the data and compare it using the DragEventArgs drgevent?
So first of all, when I grab an object from the list.
foreach (IInt d in dlist)
DoDragDrop(d.GetType(), DragDropEffects.Move);
And when I want to extract the data ie check what object was draged.
protected override void OnDragDrop(DragEventArgs drgevent)
{
if (drgevent.GetType() == typeof(DragedObject))
do stuff...
}

After finally getting to the root of this, it appears that your answer is here
if (e.Data.GetDataPresent(typeof(YourType))) {
YourType item = (YourType)e.Data.GetData(typeof(YourType));
If I am understanding you correctly, then you are looking for reflection
You can use GetType
arg.GetType() == typeof(Class1)
or is
arg is Class1
UPDATE
Without more code than provided, here is what it sounds like you need to do:
foreach (IInt d in dlist)
DoDragDrop(d, DragDropEffects.Move);
DoDragDrop sounds like it will create the DragEventArgs from the object and effect, so you would want something like this:
protected override void OnDragDrop(DragEventArgs drgevent)
{
if (drgevent.dObject.GetType() == typeof(DraggedObject))
do stuff...
}
Notice that you are not testing the arg itself, instead you are testing what it contains.

Related

How to get the type of object from a DataSource?

I'm within a Repeater and I'd like to check out which kind of object its repeating OnItemDataBound, but doing this:
public void RepeaterListato_OnItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
Response.Write(repeaterListato.DataSource.GetType());
}
it returns the whole collection's type:
System.Collections.Generic.List`1[BrLayer.Pagina]
Not BrLayer.Pagina. Is there a way?
The OnItemDataBound event handler has an argument RepeaterItemEventArgs e.
You want:
e.Item.DataItem.GetType()
Note that e.Item.DataItem will be null if e.Item.ItemType is Header, Footer, Separator or Pager; so you should check for null or check ItemType if your Repeater may have any of these elements.
Note that OnItemDataBound will be called for each item in the DataSource, and that in the general case there is no guarantee that all items will have the same Type.
It absolutely is possible! Here's a working example:
class Program
{
static List<string> MyGenericList = new List<string>();
static void Main(string[] args)
{
Console.WriteLine($"My list class's type is: {MyGenericList.GetType()}, and its first generic argument is: {MyGenericList.GetType().GetGenericArguments()[0]}");
Console.ReadLine();
}
}
Notice the call to Type.GetType().GetGenericArguments(), that's where the magic happens. It'll return you an array of all the generic arguments of the original type.

WeakSubscribe in MvvmCross doesn't work correct

Context:
I have an unknown Model-Object which contains one or more ObservableCollections.
These collections contains objects which implements INotifyPropertyChanged.
I now want to observe the PropertyChangedEvents for all objects inside the Model-Object.
What I have done:
So I wrote this method which uses reflection to find the specific objects. This all works fine. Except the part where it comes to the MvvmCross function WeakSubscribe. I really like the idea behind, but it seems it loses the reference and don't fire the event.
Strange: If I debug this code it works correct, but without breakpoints it's not working.
private void SubscribeToDetailData()
{
var tempTokenList = new List<MvxNotifyPropertyChangedEventSubscription>();
var fieldInfos =
DetailData.GetType().GetRuntimeProperties().Where(f => Helpers.IsSubclassOfRawGeneric(typeof (ObservableCollection<>), f.PropertyType));
foreach (var fieldInfo in fieldInfos)
{
var collection = fieldInfo.GetValue(DetailData) as IEnumerable<object>;
if (collection == null)
continue;
foreach (var inpc in collection.Cast<INotifyPropertyChanged>())
{
tempTokenList.Add(inpc.WeakSubscribe((sender, e) => DetailDataPropertyChanged(e.PropertyName)));
}
}
_subscriptionTokens = tempTokenList.ToArray();
}
// This method is never raised
private void DetailDataPropertyChanged(string propertyName)
{
if (_enabledFields.Evaluate(DetailData, propertyName))
RaisePropertyChanged(() => FieldEnabledState);
}
It might be that your subscribed Action is getting garbage collected.
This can be caused, I think, if the compiler creates an instance of an anonymous class to implement your anonymous Action. I wouldn't normally expect this to happen in your code because you are not using any local variables in your Action - but this could be the case.
Does your code work if you change the subscription to:
tempTokenList.Add(inpc.WeakSubscribe(DetailDataPropertyChanged));
with the method signature changed to:
private void DetailDataPropertyChanged(object sender, PropertyChangedEventArgs e)

Use reflection to get actual value of the property notified by INotifyPropertyChanged?

I am working on a project that will use INotifyPropertyChanged to announce property changes to subscriber classes.
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Quantity")
....
It appears to me that when the subscribing class receives the notification, the only available value it can get is the name of the property. Is there a way to get a reference of the actual object that has the property change? Then I can get the new value of this property from the reference. Maybe using reflection?
Would anyone mind writing a code snippet to help me out? Greatly appreciated.
Actual object is sender (at least, it should be):
void item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
var propertyValue = sender.GetType().GetProperty(e.PropertyName).GetValue(sender);
}
If you care about performance, then cache sender.GetType().GetProperty(e.PropertyName) results.
Note: this interface is primarily a data-binding API, and data-binding is not limited to simple models like reflection. As such, I would suggest you use the TypeDescriptor API. This will allow you to correctly detect changes for both simple and complex models:
var prop = TypeDescriptor.GetProperties(sender)[e.PropertyName];
if(prop != null) {
object val = prop.GetValue(sender);
//...
}
(with a using System.ComponentModel; directive)

Temporarily stop form events from either being raised or being handled?

I have a ton on controls on a form, and there is a specific time when I want to stop all of my events from being handled for the time being. Usually I just do something like this if I don't want certain events handled:
private bool myOpRunning = false;
private void OpFunction()
{
myOpRunning = true;
// do stuff
myOpRunning = false;
}
private void someHandler(object sender, EventArgs e)
{
if (myOpRunning) return;
// otherwise, do things
}
But I have A LOT of handlers I need to update. Just curious if .NET has a quicker way than having to update each handler method.
You will have to create your own mechanism to do this. It's not too bad though. Consider adding another layer of abstraction. For example, a simple class called FilteredEventHandler that checks the state of myOpRunning and either calls the real event handler, or suppresses the event. The class would look something like this:
public sealed class FilteredEventHandler
{
private readonly Func<bool> supressEvent;
private readonly EventHandler realEvent;
public FilteredEventHandler(Func<bool> supressEvent, EventHandler eventToRaise)
{
this.supressEvent = supressEvent;
this.realEvent = eventToRaise;
}
//Checks the "supress" flag and either call the real event handler, or skip it
public void FakeEventHandler(object sender, EventArgs e)
{
if (!this.supressEvent())
{
this.realEvent(sender, e);
}
}
}
Then when you hook up the event, do this:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
When WhateverEvent gets raised, it will call the FilteredEventHandler.FakeEventHandler method. That method will check the flag and either call, or not call the real event handler. This is pretty much logically the same as what you're already doing, but the code that checks the myOpRunning flag is in only one place instead of sprinkled all over your code.
Edit to answer question in the comments:
Now, this example is a bit incomplete. It's a little difficult to unsubscribe from the event completely because you lose the reference to the FilteredEventHandler that's hooked up. For example, you can't do:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
//Some other stuff. . .
this.Control.WhateverEvent -= new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler; //Not gonna work!
because you're hooking up one delegate and unhooking a completely different one! Granted, both delegates are the FakeEventHandler method, but that's an instance method and they belong to two completely different FilteredEventHandler objects.
Somehow, you need to get a reference to the first FilteredEventHandler that you constructed in order to unhook. Something like this would work, but it involves keeping track of a bunch of FilteredEventHandler objects which is probably no better than the original problem you're trying to solve:
FilteredEventHandler filter1 = new FilteredEventHandler(() => myOpRunning, RealEventHandler);
this.Control.WhateverEvent += filter1.FakeEventHandler;
//Code that does other stuff. . .
this.Control.WhateverEvent -= filter1.FakeEventHandler;
What I would do, in this case, is to have the FilteredEventHandler.FakeEventHandler method pass its 'this' reference to the RealEventHandler. This involves changing the signature of the RealEventHandler to either take another parameter:
public void RealEventHandler(object sender, EventArgs e, FilteredEventHandler filter);
or changing it to take an EventArgs subclass that you create that holds a reference to the FilteredEventHandler. This is the better way to do it
public void RealEventHandler(object sender, FilteredEventArgs e);
//Also change the signature of the FilteredEventHandler constructor:
public FilteredEventHandler(Func<bool> supressEvent, EventHandler<FilteredEventArgs> eventToRaise)
{
//. . .
}
//Finally, change the FakeEventHandler method to call the real event and pass a reference to itself
this.realEvent(sender, new FilteredEventArgs(e, this)); //Pass the original event args + a reference to this specific FilteredEventHandler
Now the RealEventHandler that gets called can unsubscribe itself because it has a reference to the correct FilteredEventHandler object that got passed in to its parameters.
My final advice, though is to not do any of this! Neolisk nailed it in the comments. Doing something complicated like this is a sign that there's a problem with the design. It will be difficult for anybody who needs to maintain this code in the future (even you, suprisingly!) to figure out the non-standard plumbing involved.
Usually when you're subscribing to events, you do it once and forget it - especially in a GUI program.
You can do it with reflection ...
public static void UnregisterAllEvents(object objectWithEvents)
{
Type theType = objectWithEvents.GetType();
//Even though the events are public, the FieldInfo associated with them is private
foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
{
//eventInfo will be null if this is a normal field and not an event.
System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
if (eventInfo != null)
{
MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
if (multicastDelegate != null)
{
foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
{
eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
}
}
}
}
}
You could just disable the container where all these controls are put in. For example, if you put them in a GroupBox or Panel simply use: groupbox.Enabled = false; or panel.Enabled = false;. You could also disable the form From1.Enabled = false; and show a wait cursor. You can still copy and paste these controls in a container other than the form.

How to detect if ASP.NET control properties contain DataBinding expressions?

I have a custom control which inherits from System.Web.UI.Control and some of its properties can be declaratively set using databinding expressions. e.g.
<foo:Foo runat="server" MyFoo="<%# this.GetFoo() %>" />
Now, when I do that I need to call .DataBind() on the control (or one of its parents) to evaluate these expressions.
What I would like to be able to do is detect if any properties were set this way and just automatically have the custom control call this.DataBind() after OnPreRender or there about.
So the question: how do I detect if databinding expressions are waiting to be executed?
I'm convinced that in some ControlBuilder or DataBindContext class lives the information needed to determine this. I've hunted around with Reflector and cannot seem to find it.
I should add, that I don't want to pay the overhead of executing DataBind() if no direct properties have been assigned this way. This is why I'd like to detect before hand. This class is extremely light but I'd like the ability to declaratively set properties without needing any code behind.
Doing some deeper looking into ControlBuilder, I noticed that the compiled factory for each control instance will attach a DataBinding event handler when there are data binding expressions present. I've found that checking for this seems to be a very reliable method for determining if data binding needs to occur. Here is the basis of my solution to the problem:
using System;
using System.Reflection;
using System.Web.UI;
public class AutoDataBindControl : Control
{
private static readonly object EventDataBinding;
private bool needsDataBinding = false;
static AutoDataBindControl()
{
try
{
FieldInfo field = typeof(Control).GetField(
"EventDataBinding",
BindingFlags.NonPublic|BindingFlags.Static);
if (field != null)
{
AutoDataBindControl.EventDataBinding = field.GetValue(null);
}
}
catch { }
if (AutoDataBindControl.EventDataBinding == null)
{
// effectively disables the auto-binding feature
AutoDataBindControl.EventDataBinding = new object();
}
}
protected override void DataBind(bool raiseOnDataBinding)
{
base.DataBind(raiseOnDataBinding);
// flag that databinding has taken place
this.needsDataBinding = false;
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
// check for the presence of DataBinding event handler
if (this.HasEvents())
{
EventHandler handler = this.Events[AutoDataBindControl.EventDataBinding] as EventHandler;
if (handler != null)
{
// flag that databinding is needed
this.needsDataBinding = true;
this.Page.PreRenderComplete += new EventHandler(this.OnPreRenderComplete);
}
}
}
void OnPreRenderComplete(object sender, EventArgs e)
{
// DataBind only if needed
if (this.needsDataBinding)
{
this.DataBind();
}
}
}
This solution disables itself if no DataBinding event handler is attached or if the control is manually data bound (directly or via a parent).
Note that most of this code is just jumping through hoops to be able to test for the existence of the event. The only reflection needed is a one-time lookup to get the object used as the key for EventDataBinding.
There is an internal ArrayList called SubBuilders on the ControlBuilder class. For each databinding expression TemplateParser enocunters, ProcessCodeBlock() adds a CodeBlockBuilder object with a BlockType property CodeBlockType.DataBinding to SubBuilders.
So if you can get a handle to the ControlBuilder you want, you should be able to reflectively iterate over SubBuilders and look for objects of type CodeBlockBuilder where BlockType == CodeBlockType.DataBinding.
Note of course this is all kinds of nasty and I'm really suspicious this is the best way to solve your core problem. If you take two steps back and look at the original problem, maybe post that on Stackoverflow instead - there's plenty of super-smart people who can help come up with a good solution.

Categories