C# Assembly Loading and Late Binding - c#

I'm reading this book on C# and .NET and I'm learning a bunch of cool stuff. I've read the part where the author talks about dynamically loading an assembly and creating an instance of a type in that assembly.
In AS3, it's possible to do the same kind of stuff, except for one thing : you can ask the compiler to not compile a set of class, but to check for type safety. Here's an example :
//Defined in an external library
public class A {...}
//In my application, I tell the compiler to type check A, but not compile it
var a:A = new A();
a.whatever();
At runtime in my application code, I can dynamically load my external library containing the definition of class A, load those definitions into my application's ApplicationDomain and everything will run fine. No needs of reflection!
Is this possible in C#?
In other words, can I instruct the C# compiler to typecheck against a bunch of class (let's say, in a library) but exclude them from compilation?

I'm not 100% clear on what the as3 code is doing - but it sounds like you want to define a common interface (in a separate dll) that your external assembly can implement - and simply cast it when you create the object:
Type type = loadedAssembly.GetType(fullyQualifiedName);
IMyInterface obj = (IMyInterface)Activator.CreateInstance(type):
now you can use methods defined on obj easily.
Alternatively, in C# 4.0 the dynamic keyword provides duck-typing.

I just read this
Action Script is a dynamic language, it offers as a "special bonus" a type check feature, it helps you catch bugs at compile time, just like static typed languages do.
C# is a static-typed language, it does all its type checking at compile time. The type check is not an "added bonus" it's an integral feature. C# has always had the ability to late-bind using reflection and the feature is getting better with the new upcoming dynamic keyword.
However, if you use any of the late-binding features that C# has, you get no type checking.

Related

C# connect with com-object

Is there in C# connect to COM-object and use contents of com-object such as in the Builder c++:
CreateOleObject("some.someClass");
(OLE C # seems to be not supported, except OLEDb, but it is not the current case in my opinion)
I know I can add a link -> COM -> Seeking a registered com-object.
But it does not fit.
Normally, if you need to use a COM object in C#, you would add it as a Reference, and select the registered type library. That will generate an Interop Assembly, after which you can use the COM object just like any other C# class.
Alternatively, you can run the .NET utility tlbimp by hand, which has roughly the same effect but gives you slightly more control.
If you really need to create the object dynamically, without knowing anything about the type ahead of time, you can use the dynamic keyword and the Activator class to create a dynamic instance of a type. The code would look like:
var comType = Type.GetTypeFromProgID("some.someClass");
dynamic obj = Activator.CreateInstance(comType);
This will defer all type checking on obj until run-time, behaving much like VBA would.

Is it possible writing code that generate a class, method, member at runtime ?

Is it possible writing code that generate a class, method, member at runtime using .NET (C#)?
For more details consider this scenario :
create a dynamic workflow program to enable user for creating his own process, activities, and writing dynamic SQL SPs, …, and collect all this stuff together then generate a classes, member variables , member functions , UIs, conditions, … dynamically at run-time ! in other word your own dynamic code factory framework !
Yes, there are various options for this:
Use CodeDOM (the System.CodeDom namespace)
Use the System.Reflection.Emit namespace
Create C# code and then compile it with Microsoft.CSharp.CSharpCodeProvider
For individual methods, create an expression tree and then compile it to a delegate
Use the Roslyn CTP to either compile C# code or create your own AST and compile that
The short response is yes. You have to look and study the following technologies:
CodeDom
Windows Wordflow Foundation
If it is anyway useful can be discussed: One able to "dynamically" program a workflow in a so specific mode will probably prefer to write the code by hand himself.
Another alternative of using strong types in this case, you may consider also using
Dynamic object to allow fully featured dynamic behaviour.
Could be more appropriate then strong typing generated at runtime, in this case.
Quick answer: Yes!
For a detail of how to achieve this you would want to start your learning by looking at Reflection.
The next step would be looking for other resources on the internet and a quick search located this question on SO:
How to create a method at runtime using Reflection.emit
Dynamic Language Runtime may also be worth a look.

Saving a C# class definition

Is there any way to save an entire class definition for a C# object to a file / data store?
I use the [Serializable] tag and ISerializable interface to do this already, but both of these rely on the object definition being in the assembly at run time.
What I'm looking for is a solution to the following scenario:
1) User creates object MyClass in my software and saves it
For the purpose of this example, MyClass is a stand-alone object that doesn't rely on any other class in the system:
i.e. this could be the entire definition:
public class MyClass
{
public int MyProperty { get; set; }
public void DoSomething() { /* do something, like Console.Write(""); */ }
}
2) We release a patch that removes MyClass from the system
3) User loads the saved MyClass from step 1 and calls DoSomething() on it - and has the function work exactly the same as it did before the patch removed the class from the system
Is there any way this can be done without reflection / emit trickery?
No, this won't work without emitting the type definition. What you are trying to do is actually save off the code (otherwise, how would DoSomething work?) - which is what the compiler does for you. Plain serialization will never work for you here.
So, if you need to save behavior as well as state, you need to either keep the historical code around, use some type of reflection emit trickery to persist the type definition as a loadable assembly, or use dynamic programming tricks that treat data as executable code.
When I have had do versioned serialization before, I normally have custom serialization logic and a "version" attribute on the object - using this I can create a type that I've moved and renamed - say SomeClass to Archive.SomeClassV3. You can use Version Tolerant Serialization for this, but I prefer to implement ISerializable and use serialization proxies if this is required. (Well, actually I prefer to avoid this problem altogether!)
Well, you could keep all of these serializable classes in their own DLLs, package the DLLs with the application, and have the DLLs loaded at runtime. That way, even if you remove the classes from the latest version of the application, the loaded DLLs will still work.
This seems like a scary approach, though ... now you have clients running ancient code that you no longer even have in your source control repository. How are you supposed to debug that?
You talking about not class-property serialization, but about process-serialization (or method-, doesn't matter). But unlike property serialization, this should contain MSIL-code that runs when you need it. So you must somehow translate it to a bin-code and then run by Assembly.Load, for example. I guess this is not an easy way to do this. So, if this is possible - store your implementation of MyClass to a separate dll, or as a string (in c# language) for further compilation and execution by reflection.

Serializing IronPython Objects Which Inherit From CLR Types

This may be a bit of a weird question, but is there any reliable way to serialize IronPython objects whose classes extend CLR types?
For instance:
class Foo(System.Collections.Generic.List[str]):
def Test(self):
print "test!"
System.Collections.Generic.List<string> is serializable with Pickle, as it implements the ISerializable interface, but emitted subclasses of serializable CLR types seem to not work, and i get ImportError: No module named Generic in mscorlib, Version=4 when running pickle.dumps(Foo()).
Additionally, running the usual Formatter.Serialize(stream, object) gives me:
SystemError: Type 'IronPython.NewTypes.System.Collections.Generic.List`1_4$4' in Assembly Snippets.scripting, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
How can I implement serialization of IronPython objects when running in an embedded C# environment?
I don't know if it is what you are after, but you could consider the python version of protobuf (here)? I haven't tested it specifically on ironpython, mind. This has the added advantage that there are also C# implementations that may help, while keeping it platform independent. When possible I want to get protobuf-net to support DLR types, but that is a big job.
As a side note, personally I'd recommend having a dedicated DTO type rather than trying to extend the inbuilt types.
Quote from clrtype metaclasses
IronPython doesn’t support Reflection
based APIs or custom attributes today
because IronPython doesn’t emit a
custom CLR types for every Python
class. Instead, it typically shares a
single CLR type across many Python
classes. For example, all three of
these Python classes share a single
underlying CLR type.
class shop(object):
pass
class cheese_shop(shop):
def have_cheese(self, cheese_type):
return False
class argument_clinic(object):
def is_right_room(self, room=12):
return "I've told you once"
import clr
print clr.GetClrType(shop).FullName
print clr.GetClrType(cheese_shop).FullName
print clr.GetClrType(argument_clinic).FullName
Even though cheese_shop inherits from
shop and argument_clinic inherits from
object, all three classes share the
same underlying CLR type
I haven't tried, but maybe you can solve this issue with manual serialization via serialization surrogates.

Which language can change class member dynamically in run time?

I know in Ruby can add and modify method of class dynamically in run time. what about other language? what is C# ,can in this language modify or add some method and ... in run time and dynamically?
I think you are looking for prototype inheritance. A list of languages is mentioned in the same wikipedia page.
There is a similar question on SO which you can look up.
Yes, in C# you can add methods at runtime through reflection and the Emitter object.
In C# 4.0 you can even do it in plain C# code with the Expando object. This is arguably closer to the Ruby way (it's practically a carbon copy if I remember correctly) and a lot easier to use.
Edit: All of this applies to all .NET languages, including VB.Net and F#.
The whole point of static type systems like C#'s is that all functionality defined for a particular type is known (and checked) at compile-time.
If you write
foo.jump(42);
the compiler verifies that whatever type foo has, it supports an operation called jump taking an integer parameter.
Recently, C# got the possibility of having dynamically checked objects through the dynamic type, which basically allows what you described in a very limited context, but nevertheless, the overall language is statically typed.
So what's left are dynamic languages like Ruby, where method existence is just checked at run-time (or call-time).
I think JavaScript can change so called prototypes to add methods to objects and basically achive the same thing as Ruby.
Python excels at this operation - here are bunch of examples: Python: changing methods and attributes at runtime
Lisp's object system is also quite dynamic:
http://en.wikipedia.org/wiki/Common_Lisp_Object_System
"CLOS is dynamic, meaning that not only the contents, but also the structure of its objects can be modified at runtime. CLOS supports changing class definitions on-the-fly (even when instances of the class in question already exist) as well as changing the class membership of a given instance through the change-class operator. CLOS also allows one to add, redefine and remove methods at runtime."
in C# 4 you have dynamic object which you can add/modify at run time.

Categories