Find "Collection" from subobject - c#

Is there a method to understand if a generic C# Object is part of a collection? And is there a way to retrieve said collection?
I know an Object is not aware of being part of another (no references stored anywhere about parents) but maybe one could use reflection on generic collections.

To answer original question : no, you're not supposed to be able to find parent collection of an object, and reflection probably won't help.
But you may be able to achieve what you need by modifying behavior of ICollection.Add() by using extension methods and storing in each added objects a reference to their common container.
Putting additional data in objects seems to be achievable, as it is stated here :
How can additional data be associated with existing objects using extension methods?
There may be other solutions to achieve what you need, but on my self I'd go with something like that.

Related

When using protobuf-net, how do I know what fields will be updated (or have been updated) when using merge on an existing object

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.

Instantiate all properties and sub properties in an object (C#.net)

I have an object (x) with about 100 properties. Most of these properties are reference types that will need to be instantiated before I can do anything with x. Also, many of the properties on x will have properties that will also need to be instantiated.
I've thought to use reflection and recursion, but I'm still a little bit stuck on how the implementation would work. My current implementation involves looping through the PropertyInfo Array, and using SetValue from Activator.CreateInstance. As I drill down through x, I'm getting a lot of exceptions:
No parameterless constructor defined for this object.
Cannot create an abstract class.
Property set method not found.
Should I just account for these cases, or is there a better way to be doing this? Ultimately, it's not assigning values to everything I need still. Thanks for your help.
Probably this is overkill, but having such a big object which appears to refer to a hierarchy of classes (you mentioned abstract classes), I'd use a properly configured DI container such as Unity, to do the work for me.
You are looking for Dependency Injection, .NET included Managed Extensibility Framework, which supports creating objects with properties and with proper lifecycle control.
However, it will still give exceptions when it cannot instantiate types, but instead of creating all types, MEF provides attributes and other ways to control what types should be instantiated.

Are instances of anonymous types serializable into a session?

Problem
I have a one time use object which is a composite of several objects and their properties. I would like to store this anonymous type into session and pull it back out again.
Questions which need answering
Is this a bad idea? If so, is there is a better way? (without creating a serializable object and storing that in session)
Also wondering if this can be done?
it is a bad idea; anon types are a poor choice outside of a single location. There is something called "cast by example", but it is not good practice. The right approach is simply "write a simple class to represent that state". With auto-props that is trivial.
Dynamic is another viable option (that can talk to anon-types), but again: what are you tryig to save here? Write the POCO/DTO already... It doesn't even need to be Serializable in many cases (unless ou have an out-of-process state server; in which case it is more important to have a known DTO).
Anonymous types are intended to be used within a single method body. Anytime you start passing them between methods you are asking for a bit of pain. It's much simpler at that point to just go ahead and define a concrete type and use that instead.
If you want to find a flexible middle ground between anonymous types and a traditional POCO, a NameValueCollection might work well for you.

Add a property to already created Type at runtime C# ASP.NET

I had a requirement of generating classes and its objects at runtime. Hence, looking at this article I created the same. (using )
I am storing all created types in a list.
But now the other requirement is to add properties to already created Types.
This is for the reason, if i want to use say Class A as a property Type in Class B and say Both in Class C.
I read a lot of articles on the same but have not yet come to a solution
Any Help will be appreciated.
Thanks
Actually, i am in process of developing a multitenant application like LitwareHR by Microsoft.
This will be a system where admin can make sub sites with same escalation management functionality (like MS sharepoint)
Everything is done except workflows!
For data to be stored in tables, i am storing it in XML format..
Eg:
<root tablename="UserInfo">
<column name=\"Name\">Miron</column>
<column name=\"Company\">IBM</column>
</root>"
Everything from controls on the page to events to validators to web parts gets created on runtime using XSLT.
Here, the challenge comes when i need to use expression evaluator to apply workflows to it.
Eg: If UserInfo.Name == "Miron"
Everything gets created on runtime, so have to retrieve table info as an object.
Let me know if i am not clear!
If the types exist then this gets very tricky; you can't add actual properties to an existing type, but if the code that *inspects *the values uses TypeDescriptor (which most data-binding does) then you can add properties sort of via custom PropertyDescriptors - either by implementing ICustomTypeDescriptor (which requires that you do something at build), or TypeDescriptionProvider.
Both are very complex, and both also demand that you have somewhere handy to put the extra data (a property-bag).
Note that in 4.0, dynamic may have some usefulness here.
If you want to avoid this, then just wrap the types in something that looks similar but with extra properties. It'll get the job done while retaining sanity.
Yes, you can use Composition as you described to do this, but classically one would use inheritence for adding functionality to an existing type.
It is difficult to answer your question without more detail about how these classes are to be used, what will be calling them and how.
I believe you will have to derive your classes from single base. Also, to be able to:
use say Class A as a property Type in
Class B and say Both in Class C.
you will have to prepare class A, in case of it being a property of B; and classes A and B ready for them to be a property in Class C.
It would be helpful if you can add more information to your question.

How do I iterate through instances of a class in C#?

Is there a way to iterate over instances of a class in C#? These instances are not tracked or managed in a collection.
Not inside the regular framework. You would need to track them manually.
You can, however, do this in windbg/sos - mainly for debugging purposes (not for routine code).
You have to have references to them somewhere, or at least know where to look, so in identifying them you'd probably put them into a collection which you'd then iterate.
If you don't know where the references live, then you'd have to have to introduce some kind of tracking mechanism. Perhaps a static collection on the type? It would have to be implemented carefully though.
Not directly.
You could conceptually have your object place a copy of itself into some well-known place (e.g. a static collection) and then use that to iterate, but then you'd have to make sure you cleared the instance out of that collection at some point or else it'll never get garbage collected.
In the comment thread on this post there is an interesting discussion and solution related to this question.
As Marc said, if you want to do it in code, you would need to keep a collection of them. If you are debugging, have a look at this blog post: http://blogs.msdn.com/tess/archive/2006/01/23/516139.aspx
If you need a collection in memory of all of the object instances of a certain type, you could consider using a collection of System.WeakRef's A weak ref is a reference that does not keep the object that it references. This would let you keep a collection of weak-refs to the object instances you want to enumerate. Have a look at Weakrefs in the help for more info.

Categories