Is there a way in .NET (C#) when using the debugger to know what collections an object is currently in.
I have a situation where class instances are moving in and out of different Lists and Arrays and am trying to track down which collections at any point in time it is currently in. i.e. when i hit a breakpoint.
The only solution I can think of is coding some kind of tracker class. Was hoping the debugger might have a way of tracing this.
Edit: I guess its kind of like the way you can expand a collection in the debugger and see the members, except I'd like to do the reverse.
Thanks.
It sounds like you would benefit from using the observer pattern, which creates a "one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically". Basically, you have an object that receives a notification whenever an item gets added to a collection.
.NET 4 has a built in implementation of this pattern. Check out Observer Design Pattern in .NET.
Interface Documentation:
IObserver
IObservable<T>
It also may be worthwhile to look at the ObservableCollection<T> class, and see if that would provide the functionality you need. It is available in .NET 3.
I don't believe there's anything like this built-in, but it would be pretty easy to create. Just add expressions to the Watch window, one per collection.
Or create a single function in your code that searches the collections and returns, say, an array of strings (collection names) - and call that function from the Watch window.
Related
Using Protobuf-net, I want to know what properties of an object have been updated at the end of a merge operation so that I can notify interested code to update other components that may relate to those updated properties.
I noticed that there are a few different types of properties/methods I can add which will help me serialize selectively (Specified and ShouldSerialize). I noticed in MemberSpecifiedDecorator that the ‘read’ method will set the specified property to true when it reads. However, even if I add specified properties for each field, I’d have to check each one (and update code when new properties were added)
My current plan is to create a custom SerializationContext.context object, and then detect that during the desearalization process – and update a list of members. However… there are quite a few places in the code I need to touch to do that, and I’d rather do it using an existing system if possible.
It is much more desirable to get a list of updated member information. I realize that due to walking down an object graph that may result in many members, but in my use case I’m not merging complex objects, just simple POCO’s with value type properties.
Getting a delta log isn't an inbuilt feature, partly because of the complexity when it comes to complex models, as you note. The Specified trick would work, although this isn't the purpose it was designed for - but to avoid adding complexity to your own code,that would be something best handled via reflection, perhaps using the Expression API for performance. Another approach might be to use a ProtoReader to know in advance which fields will be touched, but that demands an understanding of the field-number/member map (which can be queried via RuntimeTypeModel).
Are you using habd-crafted models? Or are you using protogen? Yet another option would be to have code in the setters that logs changes somewhere. I don't think protogen currently emits partial method hooks, but it possibly could.
But let me turn this around: it isn't a feature that is built in right now, and it is somewhat limited due to complexity anyway, but: what would a "good" API for this look like to you?
As a side note: this isn't really a common features in serializers - you'd have very similar challenges in any mainstream serializer that I can think of.
I was working with angular-js and came across interesting feature that can watch object for changes.
I wonder if there is something similar in c#. I thought to create some watcher that will accept object to be watched, and may be check the hash code of the object periodically to find out if object changed, then rise an event. But that seems a bit inefficient.
Any ideas?
Thanks
That wouldn't work anyway, firstly because there is no requirement for a property change to affect the hash code, and secondly, even if it did affect the hash code, it would be possible for the new hash code to be equal to the old hash code.
What AngularJS does is keep track of the last-known values, and then re-load all of the values, comparing them to the prior ones. If they're no longer equal, there has been a change.
You could do the same in C# if you want to.
But a way that's more common in C# is for the object being watched to implement the INotifyPropertyChanged interface, and raise the PropertyChanged event on each property change. This gives the object the ability to notify any interested watchers that properties have changed, without requiring the watcher to do any polling.
In both JavaScript and C#, objects aren't observable per se.
Actually, Angular turns objects into observable objects under the hoods, and since JavaScript is a dynamically-typed language this conversion or wrapping can be done in a painless way.
Since C# is a strongly-typed language, you can't observe objects if they don't implement an interface or something that can expose an event to subscribe to changes. Usually observable objects should implement INotifyPropertyChanged interface.
Other way of implementing this is using a framework like Castle DynamicProxy to create proxies of your classes and intercept both method calls and property gets and sets.
Background
After spending a lot of time researching, I have not found any way of assigning multiple objects to PropertyGrid (Extended WPF Toolkit). My next idea is to create my own aggregator class that takes in selected objects and exposes their common properties to the outside world. I'll then assign (an instance of) this class to PropertyGrid. Any changes made by the user in PropertyGrid will be passed on to the selected objects by the aggregator class.
Question
Is there anything in the Framework (especially Reflection) that could help me with this task? All objects in my domain inherit from a common ancestor and add new properties of their own (or override ancestor versions). Class hierarchy is multiple levels deep.
UPDATE
For anyone else stuck in the same situation as me, I was able to finally solve PropertyGrid problem. See my other post for the solution.
Hope I can interpret what you want correctly.
One of the idea is using T4ToolBox to generate pre-compile class by scripting (which is also C# code in a template file).
Define your objects that want to be aggregate into xml.
Then you can use reflection to loop through all public method/properties in the objects (based on the xml) to find out the set of common methods
Generate an interface and (if you want) the corresponding concrete classes
One manual work after this is change your original object by implementing the newly generated interface.
I'm primarily an Objective-C/Cocoa developer, but I'm trying to implement the Observer pattern in C#.NET, specifically mimicking the NSKeyValueObserving protocols and methodology.
I've gotten as far as mimicking NSKVO with manual support, as described in Apple's KVO Programming Guide (see http://tinyurl.com/nugolr). Since I'm writing the setValue:forKey: methods myself, I can implement auto KVO notification through there.
However, I'd like to somehow implement auto KVO on all properties by dynamically overriding them at runtime. For example, replacing Button.Title.set with:
set {
this.willChangeValueForKey("title");
title = value;
this.didChangeValueForKey("title");
}
So, this is my question:
How do I dynamically override a method or property at runtime in C#? I've gotten as far as getting and invoking methods and properties by name using Reflection.MethodInfo. Alternatively, can I observe the runtime and find out when a method is about to be/has been called?
Dynamic metaprogramming and aspect oriented programming are not yet strongly supported in C#. What you can do, is look at a free tool called PostSharp - it allows supports weaving aspects into your code around properties and method calls quite easily.
You can implement the INotifyPropertyChanged interface (without postsharp) and it can be used in certain contexts to notify observers that a value of a property has changed. However, it still requires that each property actually broadcast the change notification - which generally requires it to be specifically coded to support that. Injecting change notification to existing code (without actually changing the source) is not an easy thing to do in straight-up C#. PostSharp (other other AOP/dynamic proxy libraries) make this sort of thing dramatically easier.
I'm not sure if you need to go down this road or not. But if you want to implement overrides of a method (i.e. generating new code for the method?) then it is possible with Emit. I would explore any other suggestions first before diving into those deep waters.
You're looking for INotifyPropertyChanged. You can dynamically implement that using PostSharp, Castle DynamicProxy or probably any other proxying library.
This does not solves the problem of having to add the tracking code dynamically, but can be interesting to read: Trackable Properties with Weak Events
With this stuff you are able to track changes to specific properties and it makes easier to implement INotifyPropertyChanged (i.e. track changes to all properties).
After doing extensive research on this subject, it appears that I can't do exactly what I'd like to do with .NET in its current state.
PostSharp's method is done at compile time, meaning I can't dynamically insert my own implementations to methods.
Reflection.Emit allows me to do this dynamically, but it generates a new instance of the created subclass - I need to do this so it works with the original instance.
INotifyPropertyChanging and INotifyPropertyChanged would be perfect if any of the existing .NET classes actually used them.
... so, at the moment I'm a bit stuck. I've put a more detailed piece on what I'm doing and how I'm trying to achieve in a post on my blog. Here's hoping .NET 4.0's dynamic dispatch will help!
I am working on a Windows Forms app for quite some time now, and I really find myself doing more typecasts in the GUI code than I ever did in my underlying business code.
What I mean becomes apparent if you watch the ComboBox control that accepts some vague "object" as it's item.
Then you go off and may display some DisplayMember and a ValueMember and so on.
If I want to retrieve that value later I need to typecast my object back to what it was. Like with strings getting the value takes
string value = (string)combobox1.SelectedItem;
Since there are generics in the Framework for quite some time now, I still wonder why in the Hell not one control from the standard toolbox is generic.
I also find myself using the .Tag property on ListViewItems all the time to keep the displayed domain object. But everytime I need to access that object I then need another typecast.
Why cant I just create a ComboBox or ListView with items of type ListViewItem
Am I missing something here or is this just another example of not perfectly well thought through controls?
While the criticism of "didn't use generics" can't be fairly applied to controls developed before their existence... one must wonder about WPF controls (new in .NET 3.0, after generics in .NET 2.0).
I checked out the AddChild method in ComboBox. It takes an object parameter (ugh).
This control is intended to be used primarily via XAML. Was this done this way because there is no way to specify a type parameter in XAML? (aside, is there no way to specify a type parameter in XAML?)
Sorry to have no definitive "Why" answer, just sharing the common misery of needing to cast when working with the UI.
I dont think you're missing anything.
It's just that these classes were created back in the pre-Generics days, and WinForms is simply not cutting edge enough for MS to spend a lot of time changing or extending the API.
I often create wrapper classes for controls. This allows me to use generics. This is often in conjunction with Reflection, which is not type safe at compile time, but can be at run time.
A common source of this problem, I think, is not separating your view/presentation logic from your in-memory data model logic. Which, unfortunately, is an architecture fault that WinForms and the Visual Studio GUI designer are complicit in.
WinForms and the VS designer do not encourage the programmer to separate the management of their data objects from the form classes themselves. It would probably be better if the ComboBox ListViewItem objects didn't offer any support for arbitrary objects, either via generics or Object collections..
Unless you are hacking together something of limited use and lifetime, you should try to avoid storing references to individual data objects right in your controls or forms. They should be managed separately, and if they need to be referenced, it should be done via a model management class designed for the particular type of view class you're working with.
A simple-ish bandage for the problem, though, might be to "map" the text representations that you place into the ComboBox or ListView to the original objects, using a Dictionary field member on your Form class. It's not an ideal solution, but gives you at least a half-step of indirection between your data and your UI controls, which can make your code easier to maintain.
Edit: This is admittedly separate from the ListViewItemCollection class exposing Object instances... The official defense is likely to be that they wanted to support the standard IEnumerable and ICollection interfaces. But there's no reason they couldn't have also provided type-specific overrides of these methods, since it is designed explicitly to store ListViewItem instances. So I have no answer for you on that particular question.
Well, if you data-bind your controls to a DataBindingSource, you can get at your data that way, but AFAIK that's still not strongly typed. If you are displaying multiple parameters/aspects of a single business object, you can bind to that, then access the (strongly typed) members instead -- of course, this all goes back to Turbulent Intellect's answer, which is better separation between model and view. Still, I agree that generic-based typing would help.
It is possible (you can make your own generic controls, if you wish), but the form designer that comes with Visual Studio will freak out if you do this. You'll have to do stuff without it.
You aren't the first one to think of this, and Microsoft has already received a fair share of criticism from the public for this. Let's hope they add support for this in the future.