How to properly emit and use class? - c#

I am facing "chicken or the egg" dilemma.
Finally, after many hours of struggling with CIL, I have created an instance of class that was generated by using System.Reflection.Emit & Activator.CreateInstance() method. However, because class is dynamic, Visual Studio is not aware of the class, so I can't really code with it. How do I make it usable and accessible to other code ?
Clarification:
I have created a dynamic class that represents content of UI ListBox. Users can go in, and change the content of ListBox, generating new class. I need to make my dynamic class to be usable by rest of the application, that is not really aware of this new type/class.

You can't make it available statically. You need to use some kind of dynamic access. Or, make the class implement an interface and cast instances of that class to the respective interface type.
A very easy solution is to use dynamic if member names are statically known.

Related

Writing a properties aggregator

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.

Overwrite built in .NET class

if i inherit from a class such as System.Windows.Forms.Control and create System.Windows.Forms.NewControl, is there a way of forcing .NET to use my System.Windows.Forms.NewControl class as System.Windows.Forms.Control so that all built in controlls use my System.Windows.Forms.NewControl?
ie. i would like to make some base changes to how controls work, and i would like those changes to be reflected in ALL controls without having to subclass every single control type.
i know that extension methods will not work for this as they need to be called explicitly, and i am looking to alter properties as well as methods.
No, you cannot do anything like this. The idea behind OO is that people who write code adhering to the contract and behavior of an existing class can trust that the class will continue to behave how it's designed without worry about user interference. This isn't a dynamic language like Ruby.

How to remove duplicate code across Custom Control Classes

I have 2 custom server control classes. One inherits from TextBox and the other inherits from Label.
Both classes contain quite a lot of common code (various properties and attribute rendering logic), but the classes do contain some distinct code as well.
Ideally, the common code would be contained in an abstract class, and each custom control would inherit from that abstract class. This is not possible of course, because they already inherit from their respective base classes and c# doesn't support multiple inheritence.
How do I resolve the code duplication issue?
It depends on the exact functionality. If there is no way for them to inherit from the same place (as seems to be the case) then the best bet is to have a third class that contains the common functionality and include that in some way, either by having an instance of it in your control classes or by just calling static methods on it. Which I'd go for is probably dependant on what your code is and would hopefully be relatively obvious.

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.

Is there a way to derive from a class with an internal constructor?

I'm working with a 3rd party c# class that has lots of great methods and properties - but as time has gone by I need to extend that class with methods and properties of my own. If it was my code I would just use that class as my base class and add my own properties and method on top - but this class has an internal constructor. (In my opinion it was short sited to make the constructor internal in the first place - why limit the ability to subclass?)
The only thing I could think of was to create method / properties on my class that simply called into theirs - but it's acres of code and, well, it just doesn't "feel" right.
Is there any way to use this class a base class?
You ask: "Why limit the ability to subclass?"
Because designing for inheritance is tricky, particularly if you're designing for other developers to inherit from your class. As Josh Bloch says in Effective Java, you should design for inheritance or prohibit it. In my view, unless you have a good reason to design for inheritance, you shouldn't do so speculatively.
Does the class implement an interface which you could also implement (possibly by proxying most calls back to an instance of the original)? There's often no really elegant answer here - and the best solution will depend on the exact situation, including what you're trying to add to the class.
If you're not adding any more state - just convenience methods, effectively - then extension methods may work well for you. But they don't change what data an object is capable of storing, so if you need to add your own specialised data, that won't work.
Sounds like a perfect application for extension methods:
MSDN extension method docs
"Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type."
If the class has an internal constructor, and there are no public constructors, then that suggests that the designers did not intend for it to be subclassed. In that case, you can use encapsulation, or you can use extension methods.
Only if your class lives in the same assembly as the class you want to inherit from. An internal constructor limits the concrete implementations of the abstract class to the assembly defining the class. A class containing an internal constructor cannot be instantiated outside of the assembly.
Resharper has a nice feature to create delegating members.
Here is a sample of what you can do with it. It takes a couple of seconds.
I will not discuss whether you can build your own Facade around that 3rd party class. Previous authors are right, the library could be designed in the way that will not allow this. Suppose they have some coupled classes that have singletons that should be initialized in specific order or something like this - there may be a lot of design mistakes (or features) that 3rd party developers never care about, because they do not suppose that you will use their library in that way.
But OK, lets suppose that building a facade is not an impossible task, and you have in fact only one problem - there are too many methods you have to write wrappers around, and it is not good to do this manually.
I see 3 solutions to address exactly that problem
1) I suppose that new "dynamic" types of .NET 4.0 will allow you to workaround that problem without having to write "acres of code"
You should incapsulate an instance of 3rd party class into your class as a privare member with dynamic keyword
Your class should be derived from Dynamic or implement IDynamicObject interface. You will have to implement GetMember/SetMember functions that will forward all calls to the encapsulated instance of 3rd party class
Well, c# 4.0 is a future, Let's see on other solutions:
2) Do not write code manually if you have significant number of public methods (say more then 100). I would write a little console app that uses reflection and finds all public members and then automatically generates code to call encapsulated instance. For example
public type MethodName(params)
{
this.anInstanceOf3rdPartyClass.MethodName(params);
}
3) You can do the same as 2, but with the help of existing reflection tools, for example RedGate .NET Reflector. It will help you to list all classes and methods signatures. Then, paste all this in Word and a simple VB macro will let you generate the same code as you could do in 2.
Remark: As soon as you are not copying the code, but only copying method signatures, that are publicly available, I don't think you will violate the license agreement, but anyway it worth to re-check

Categories