I have a project which reads an external DLL through reflection and
System.Reflection.Assembly BuildDll = System.Reflection.Assembly.LoadFrom(System.AppDomain.CurrentDomain.BaseDirectory + BuildDllName);
Type BuildWindow = BuildDll.GetType(BuildFormType);
System.Reflection.MethodInfo constructors = BuildWindow.GetMethod("Initialize");
lMethod = BuildWindow.GetMethod("Submit");
TypeUserControl = Activator.CreateInstance(BuildWindow);
In this code I load the DLL and read its two methods Submit(to call this method to perform some actions) & Initialize(to pass the data required by DLL)
Now I have to return a function's result from my code to the DLL on a button event of that external DLL, there is a method in my code which returns the desired integer value
int GetValue(string id, int key)
In the external DLL a delegate is been defined as
private System.Delegate _BaseFunction;
public Delegate BaseFunction
{
set { _BaseFunction= value; }
}
On button Click event of external DLL result needed to be displayed
private void btnBaseInvoke_Click(object sender, RoutedEventArgs e)
{
object[] parameters = new object[2];
parameters[0]= Convert.ToString(txtParam30.Text.Trim());
parameters[1]= Convert.ToInt32(txtParam31.Text.Trim());
object obj = _BaseFunction.DynamicInvoke(parameters);
MessageBox.Show(Convert.ToString(obj));
}
What I am not getting is how will I initialize this delegate in my code & pass these parameters to my function?
The external DLL is a bit annoying in using a System.Delegate instead of a more specific delegate, but this is still very easy to solve.
To turn your GetValue method into a delegate, you can just do something like this:
var delegate = (Func<string, int, int>)GetValue;
That's it :)
Since you're using reflection (Do you have to? Isn't there an interface you could use instead or something? Do you have to load the assembly dynamically in the first place?), you may need to manually convert the resulting delegate to Delegate (which is just another cast), but I'm not sure if even that is necessary. Just call the setter on the property and pass it the delegate and you should be fine.
Did you try MethodBase.Invoke Method (Object, Object[])?
Maybe this will help you?
... and have it take effect?
I'd like to defer setting the ExecutionDataflowBlockOptions.SingleProducerConstrained property until I'm ready to link the network together. (Because, I want to separate creating the blocks, with their semantics, from linking the network together, with its semantics.)
But as far as I can tell you can only set the ExecutionDataflowBlockOptions when the block is created (e.g., for TransformBlock, TransformManyBlock, etc, you pass it in to the constructor and it is not visible otherwise).
However ... it hasn't escaped my notice that the properties have public setters. So ... can I create the block with a placeholder instance of ExecutionDataflowBlockOptions and hold on to it so that I can later set SingleProducerConstrained=true if I desire, when linking the blocks together (and that it will take effect)?
(BTW, is there any way to tell if SingleProducerConstrained is having any effect other than measuring throughput?)
Update: #i3amon correctly pointed out in his answer this can't be done because dataflow blocks clone the DataflowBlockOptions you pass in and use that. But I did it anyway, using internal data structures I can access via reflection and dynamic. I put that in an answer below.
It isn't possible. Modifying the options after the fact won't work. The options are cloned inside the block's constructor. Changing the options later will have no effect.
You can see examples of that here and here and it's simple to verify:
var options = new ExecutionDataflowBlockOptions
{
NameFormat = "bar",
};
var block = new ActionBlock<int>(_ => { }, options);
options.NameFormat = "hamster";
Console.WriteLine(block.ToString());
Output:
bar
Let me answer my own question. Using information from DotNetInside's decompile of the Dataflow assembly, for example, TransformBlock here (thanks #i3amon again for the link to dotnetinside.com), and the very nice ExposedObject package at codeplex here (which I learned about at this blog post, I did the following:
The TPL Dataflow blocks all implement debugger visualizers via the DebuggerTypeProxy attribute, which, applied to a type, names another type to use in the Visual Studio debugger whenever the original type is to be displayed (e.g., watch window).
Each of these DebuggerTypeProxy-named classes are inner classes of the dataflow block the attribute is attached to, usually named DebugView. That class is always private and sealed. It exposes lots of cool stuff about the dataflow block, including its genuine (not a copy) DataflowBlockOptions and also - if the block is a source block - an ITargetBlock[], which can be used to trace the dataflow network from its start block after construction.
Once you get an instance of the DebugView you can use dynamic via ExposedObject to get any of the properties exposed by the class - ExposedObject lets you take an object and use ordinary method and property syntax to access its methods and properties.
Thus you can get the DataflowBlockOptions out of the dataflow block and change its NameFormat, and if it is an ExecutionDataflowBlockOptions (and you haven't yet hooked up the block to other blocks) you can change its SingleProducerConstrained value.
However you can't use dynamic to find or construct the instance of the inner DebugView class. You need reflection for that. You start by getting the DebuggerTypeProxy attribute off your
dataflow block's type, fetch the name of the debugging class, assume it is an inner class of
the dataflow block's type and search for it, convert it to a closed generic type, and finally
construct an instance.
Be fully aware that you're using undocumented code from the dataflow internals. Use your own
judgement about whether this is a good idea. In my opinion, the developers of TPL Dataflow did a lot of work to support viewing these blocks in the debugger, and they'll probably keep it up. Details may change, but, if you're doing proper error checking on your reflection and dynamic use of these types, you will be able to discover when your code stops working with a new version of TPL Dataflow.
The following code fragments probably don't compile together - they're simply cut&pasted out of my working code, from different classes, but they certainly give you the idea. I made it work fine. (Also, for brevity, I elided all error checking.) (Also, I developed/tested this code with version 4.5.20.0 only of TPL dataflow, so you may have to adapt it for past - or future! - versions.)
// Set (change) the NameFormat of a dataflow block after construction
public void SetNameFormat(IDataflowBlock block, string nameFormat)
{
try
{
dynamic debugView = block.GetInternalData(Logger);
if (null != debugView)
{
var blockOptions = debugView.DataflowBlockOptions as DataflowBlockOptions;
blockOptions.NameFormat = nameFormat;
}
}
catch (Exception ex)
{
...
}
}
// Get access to the internal data of a dataflow block via its DebugTypeProxy class
public static dynamic GetInternalData(this IDataflowBlock block)
{
Type blockType = block.GetType();
try
{
// Get the DebuggerTypeProxy attribute, which names the debug class type.
DebuggerTypeProxyAttribute debuggerTypeProxyAttr =
blockType.GetCustomAttributes(true).OfType<DebuggerTypeProxyAttribute>().Single();
// Get the name of the debug class type
string debuggerTypeProxyNestedClassName =
GetNestedTypeNameFromTypeProxyName(debuggerTypeProxyAttr.ProxyTypeName);
// Get the actual Type of the nested class type (it will be open generic)
Type openDebuggerTypeProxyNestedClass = blockType.GetNestedType(
debuggerTypeProxyNestedClassName,
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
// Close it with the actual type arguments from the outer (dataflow block) Type.
Type debuggerTypeProxyNestedClass =
openDebuggerTypeProxyNestedClass.CloseNestedTypeOfClosedGeneric(blockType);
// Now create an instance of the debug class directed at the given dataflow block.
dynamic debugView = ExposedObject.New(debuggerTypeProxyNestedClass, block);
return debugView;
}
catch (Exception ex)
{
...
return null;
}
}
// Given a (Type of a) (open) inner class of a generic class, return the (Type
// of the) closed inner class.
public static Type CloseNestedTypeOfClosedGeneric(
this Type openNestedType,
Type closedOuterGenericType)
{
Type[] outerGenericTypeArguments = closedOuterGenericType.GetGenericArguments();
Type closedNestedType = openNestedType.MakeGenericType(outerGenericTypeArguments);
return closedNestedType;
}
// A cheesy helper to pull a type name for a nested type out of a full assembly name.
private static string GetNestedTypeNameFromTypeProxyName(string value)
{
// Expecting it to have the following form: full assembly name, e.g.,
// "System.Threading...FooBlock`1+NESTEDNAMEHERE, System..."
Match m = Regex.Match(value, #"^.*`\d+[+]([_\w-[0-9]][_\w]+),.*$", RegexOptions.IgnoreCase);
if (!m.Success)
return null;
else
return m.Groups[1].Value;
}
// Added to IgorO.ExposedObjectProject.ExposedObject class to let me construct an
// object using a constructor with an argument.
public ExposedObject {
...
public static dynamic New(Type type, object arg)
{
return new ExposedObject(Create(type, arg));
}
private static object Create(Type type, object arg)
{
// Create instance using Activator
object res = Activator.CreateInstance(type, arg);
return res;
// ... or, alternatively, this works using reflection, your choice:
Type argType = arg.GetType();
ConstructorInfo constructorInfo = GetConstructorInfo(type, argType);
return constructorInfo.Invoke(new object[] { arg });
}
...
}
Summary
I tried to achieve inheritance and encapsulation properly in javascript like it was in a class-based language such as c#.
The ugly part is the protected members have multiple copies in the private instances which are only accessible via closure, and I don't have an idea except refreshing those members to the private instances.
If it is possible, I want to get rid of both transmit and transfer in my code of Function.extend.
Update
For people who are interested in citing or research, here's the source code repository:
https://github.com/kenkins/Function.extend
The story
Since assemblies may be a concept which is out of range of javascript, I don't take the internal modifier into account, but public, protected and private.
public and private modifiers are not that difficult to achieve; but with inheritance, protected is significantly tricky. Yet it's not a recommended thing to do with javascript, most of articles I've read says prefix with a special character and document it.
But it seems I'm persisted to make javascript to simulate class-based languages .. I stole this idea and implemented in my way, the code is at rear of this post.
The idea behind the scene is to put higher accessibility with a higher prototype and access the highest one with a closure.
Say we have three prototypes A, D and G, it looks like
As it is not possible that an object is an instance of a type also of another type which is not in the prototype chain; the way I chosen is to chain the protected level horizontally and copy the members from the prototype of the declaring type. This makes nesting class possible, because the members declared on a less-derived type can be propagated to more-derived types; the transmit method in my code is to do this. If A, D and G have their own protected members, it would look like:
The closure for accessing the private instance, is this['']. It takes an argument which is for identifying a class. The modifiers holder is just the class identifier, named y in Function.extend and _ in the test code, it should not be exposed outside the class declaration. It is also used as a shortcut of this[''].
_['base'] is in fact not only the base constructor invoker, but also the private instances creator. It creates the private instances and updates this[''] for each constructor with the inheritance, so it should always be called in the constructors.
Although a private instance would have the access of the public members, it should not be used to alter them, since this[''] is not guaranteed to be invoked when accessing public members. But the accessing of private instance is; recent remembers the most recently accessed private instance, and update the protected members if there're changes.
My question is, how can I get rid of this kind of refreshing the protected members? Are there better ideas to achieve the encapsulation more of the realistic?
p.s.: I actually do not want a solution which uses non-standard methods/properties .. and it would be better there're polyfills if the used methods/properties are too fashion to the old browsers.
Function.extend
Function.extend=function(base, factory) {
factory.call(initializeClass);
updateStaticMembersOfDerivedInnerClasses(y['public'].constructor);
transfer(y['protected'], y['public']);
return y['public'].constructor;
function y($this) {
return $this[''](y);
}
function transfer(target, source, descriptor) {
if(target!==source?
'undefined'!==typeof target?
'undefined'!==typeof source:
false:false) {
var keys='undefined'!==typeof descriptor? descriptor:source;
for(var key in keys) {
if(Object.prototype.hasOwnProperty.call(source, key)) {
target[key]=source[key];
}
}
}
}
function updateStaticMembersOfDerivedInnerClasses(outer) {
var member, inner;
for(var key in outer) {
if(Object.prototype.hasOwnProperty.call(outer, key)?
(member=outer[key]) instanceof outer?
outer!==(inner=member.constructor):
false:false) {
transfer(inner, outer);
}
}
}
function initializeInstance() {
var $this=Object.create(y['private']);
var derivedGet=this[''];
var recent=$this;
this['']=function(x) {
var value=y!==x? derivedGet.call(this, x):$this;
if(value!==recent) {
transfer(value, recent, x['protected']);
recent=value;
}
transfer(value, this);
return value;
};
base.apply(this, arguments);
$this['']=this[''];
}
function initializeClass(derived) {
y['public']=Object.create(base.prototype);
y['public'].constructor=derived;
if(Object.prototype.hasOwnProperty.call(base, 'transmit')) {
base.transmit(y);
}
else {
y['protected']=Object.create(y['public']);
}
y['private']=Object.create(y['protected']);
y['base']=initializeInstance;
transfer(derived, base);
derived.transmit=function(x) {
if(x['public'] instanceof derived) {
x['protected']=Object.create(y['protected']);
x['protected'].constructor=x['public'].constructor;
}
};
derived.prototype=y['public'];
return y;
}
};
test code
'use strict';
var BaseClass=Function.extend(Object, function () {
var _=this(BaseClass);
var NestedClass=Function.extend(BaseClass, function () {
var _=this(NestedClass);
function NestedClass(x, y, z) {
_['base'].apply(this, arguments);
_(this).Y=y;
_(this).Z=z;
}
_['public'].SetX=function (x) {
_(this).InternalSetX(x);
};
_['public'].GetX=function () {
return _(this).InternalGetX();
};
_['public'].GetY=function () {
return _(this).Y;
};
_['public'].SetZ=function (z) {
_(this).Z=z;
};
_['public'].GetZ=function () {
return _(this).Z;
};
_['private'].Y=0;
});
function BaseClass(x) {
_['base'].apply(this, arguments);
_(this).X=x;
}
_['protected'].InternalSetX=function (x) {
_(this).X=x;
};
_['protected'].InternalGetX=function () {
return _(this).X;
};
_['private'].X=0;
_['protected'].Z=0;
BaseClass.Sample=new NestedClass(1, 2, 3);
});
var DerivedClass=Function.extend(BaseClass, function () {
var _=this(DerivedClass);
function DerivedClass(x, y, z) {
_['base'].apply(this, arguments);
}
});
var o=DerivedClass.Sample;
alert(o.GetX());
alert(o.GetY());
alert(o.GetZ());
o.SetX(3);
o.SetZ(1);
alert(o.GetX());
alert(o.GetY());
alert(o.GetZ());
I also had a similar thought and decided to try write something. A vanilla js solution. Still early but I like what came out of it. You might find it interesting also.
It's not exactly c# but provides a more strict ecosystem. And some other advanced js features in a lightweight solution.
https://github.com/iamlothian/rucksack.js
This is not a solution to your code, but solution to your concept. If your goal was the get your idea to work then by all means continue as I am interested by the result.
If you like me just want a more structured js environment, then here is one I wrote with similar ambition to your questions concepts.
Part 2:
The idea here is to use closure and access restriction to create a pattern that restricts the way code can be used and changed after is has been defined. For the most part a lot of the hard work has been done. But the pattern is left for you to define.
Here is a quick mock example demonstrating how you might implement a public|protect|private inheritance. I am trying to decide weather i implement some of this as a built in feature or leave it up to users to implement their own object extension like i have in the example.
http://plnkr.co/edit/ao2hTyBV1b3nYIwr7ZS5
The implementation is in scripts.js. view you console to see what is going on.
What rucksack provides is a framework for creating detached modules of code. These modules are grouped into namespaces and can depend on each other. These dependencies are resolved lazily as defined, so that definition order is not really important. The resolution process provides some other useful features such as interfaces matching and sealed module.
current features:
Modular
Dependency Injection
Factory constructor (Instances Object)
Service constructor (Static Objects)
Lazy loading
Easy error logging (All error within modules are captured and can be passed on)
Namespaces
Sealable modules and namespaces (modules that can't be accessed from outside the namespace)
Global await event for module
Interface for optional config object
Optional strict interface checks for injection
While the code with closure might solve what you want, I would go with the simpler Privileged methods as Crockford called them here.
Usage idea is simple:
Define privileged method on the base object (with limit 1 - allows to be called only once).
Privileged method returns a protected interface of itself (of a base object) which contains protected functions in it (probably those functions are privately defined in the base, and then get copied over to the protected interface object... or maybe the protected interface exists privately).
Each object extends its protected interface with its base object's protected interface and still exposes it through the privileged method.
You will end up with something like this:
function A() {
var protected = {
protectedA: function() { }
};
this.getProtected = (function() {
var allow = true;
//privileged function.
return function() {
if (allow) {
allow = false;
return protected;
}
};
});
}
//B - derives from (extends) A
function B() {
var base = {}; //acquiring a base omitted - depends on your implementation.
var protected = {
protectedB: function() { }
};
//"extend" simply copies new members into protected:
protected = $.extend(protected, base.getProtected());
this.getProtected = function() {
/* privileged function - similar to A.getProtected */
};
}
JavaScript has limited abilities in this extent, so the protected sugar comes with some cost anyway.
Javascript is a wide language, because you can do almost all the things do you want in a webpage, just by creating functions and finding ways to do it.
I can tell you that JavaScript are not a secure language, because you can easily access the most part of variables and functions, read them, and know how it works, just by acessing the .js file, included on the page.
My Tought: Some access modifiers was not created to use in javascript due to developers already know that maybe it can be useless, because JavaScript does not "Travel" into another places(pages), unless you use a session variable.
And about that modifiers:
Private
Protected
Public
I can tell you that i know some javascript modifiers that have some similarity to them, that are:
Local:
var Variable = 0;
Automatically, this is converted into a Integer variable, because it is receiving a Integer value, and too, this is a LOCAL variable because of the var modifier that declare this variable in a way that you cannot access the value of it, unless if you are inside the same function that this variable was declared.
Example:
If you declare these functions this way, with default modifiers:
function conflict(){
i = 2;
changeI();
alert(i);
}
function changeI(){
i = 0;
}
In this case the i is the same variable for the two functions.
So if you execute conflict(); you will get a alert resulting 0.
BUT, if you declare i using the var modifier:
function conflict(){
var i = 2;
changeI();
alert(i);
}
function changeI(){
var i = 0;
}
In this case, you have two i variables, because they are restricted to use only inside their function, so if you execute conflict(); now, you will get a alert with value of 2.
Class Variable:
this.Variable = "a";
This variable is automatically a String, because it is receiving a String value, Probably you already know what the this modifier does, but, i'll try to explain with my point of view, that is this variable is coming from the SuperClass or in javascript a "SuperFunction" that can be called a Class, or in other words, the "father" class.
A example:
function TClass()
{
this.getVar = function()
{
try
{
return "test";
}
catch(err)
{
return false;
}
}
this.alertVar = function()
{
try
{
alert(this.getVar());
}
catch(err)
{
alert('error');
}
}
}
var $Class = new TClass();
As you see above, i created a Class TClass and some variables containing functions into it (javascript closure) and added the modifier this. to them, to make them bound to the TClass and as you see on the alertVar() function, i access on the alert(this.getVar()); the function that are from the TClass that is equal to this in this context.
And this part: var $Class = new TClass(); i am creating the class as you probably knew that, to have access to its methods, doing this i am possible to execute, to test:
$Class.alertVar();
And getting as result, an alertbox containing "test", as you can see:
Note that you can't access the TClass methods in another ways, you only can access it creating the class and accessing by it.
So i hope that you did understand the usability of the this modifier.
Global:
window.Variable = true;
Automatically javascript declare this variable is a boolean, because it is receiving a Boolean value. The window modifier as it says, you can access it whatever you are on the window that you are, because javascript variables when declared, they go to the DOM into the window, see what is DOM:
DOM(Document Object Model): The DOM, is a multi-platform that represents how the html,xhtml, and xml markup's are organized and read by the browser that you are using. In other words, if you access the DOM you can see every propery, every variable, or such of thing that exists on the browser at the moment.
Different from another variables, the window variables can have assigned another value and access the actual value, from whatever you are, inside a function or not, inside a js file or not.
Example of Global(window):
Execute on the onLoad event of a page a code that declares a window variable, or declare it yourself using browser console:
window.Variable = true;
Then, add a JS File containing this function, or create it yourself just by executing the code on the browser console:
function testGlobalVar(){
if (Variable)
alert("it works!");
}
When you execute testGlobalVar() you will get the alert, but it is only because you declared it as `window´ otherwise, you will get nothing.
Default Modifier:
Variable = 0.5
Automatically this Variable is declared as Float beacuse it is receiving a Float value. I dont know if you already know, but javascript variables declared as the usual way, have a default modifier that makes the variable similar to window variables, but you cannot access it from whatever you are, but in most cases you can acess it, particulary, i dont know all the cases that you cannot access it, but i know that you cant when you loaded a js file and it was declared inside it. Only if you run a function that declares it, and after that try to acesss.
By the way, i see that you want to know modifiers that match the three that you said, but at my tought some of that modifiers that i told you can be used to do the same that your c# modifiers do.
I hope that you understand what i'm saying.
Ah, and if you was confused when you saw a function inside a variable, study Javascript Closures, you will understand after that :).
How the parent and child classes interact with each other
An extending child class calls super.call, a function that constructs an instance of it's parent.
A parent class shares it's protected members (both fields and functions) to it's extending subclass by using this.share in it's constructor.
A subclass can also call super.fetch(), which returns the object of fields/functions that the parent class passed to this.share
To illustrate my technique, the following code demonstrates some essentials to OOP with a simple example of a class Dog extends Animal
Some core functions for this object oriented model
// runs in both node.js and browser
var global_namespace = ('undefined'==typeof module)? window: global;
// put a no-operation function in the value for `share` in case nothing is extending a class
var not_extendable = {share:function(){}};
// when something is extending a class...
var extendable = function(constructor) {
// create a space for protected fields
var protected_space = {};
// the following is what will get passed as `this` to the parent constructor
var sharing = {
share: function(fields) {
protected_space = fields;
},
};
// the following is what will get passed as the first arg to the child constructor
return {
// enables child to call its parent's constructor
call: function(args) {
return constructor.apply(sharing, args);
},
// allows child to access protected fields shared by its parent
fetch: function() {
return protected_space;
},
};
};
Animal class
// class definition for `Animal`
(function(namespace) {
// construct an instance of this class
var constructor = function(name, weight, info) {
// private fields
var color = (info && info.color) || 'unknown';
// for protected fields
var protect = {
weight: weight,
noise: function() {
return 'nothing';
},
};
// share the protected fields with any subclass that might be extending this
this.share(protect);
// public fields and methods
return {
speak: function() {
console.log(name+' says '+protect.noise());
},
feed: function() {
console.log(name+' is not hungry');
},
weigh: function() {
console.log(name+' weighs '+protect.weight+' lbs');
},
toString: function() {
return '{Animal}';
},
};
};
// handle calls to: `Animal()`
namespace.Animal = function() {
// called with new operator: `new Animal(...)`
if(this !== namespace) {
// construct simple instance of this class
return constructor.apply(not_extendable, arguments);
}
// static call: `Animal(...)`, means the caller wants to extend this class
else {
// reference child constructor
var child_constructor = arguments[0];
// return a wrapped constructor function
return function() {
// call child constructor and allow it to call the super constructor
return child_constructor.apply({}, [extendable(constructor), arguments]);
};
}
};
})(global_namespace);
Dog class
// class definition for `Dog`
(function(namespace) {
// class `Dog` extends class `Animal`
var constructor = Animal(function(super_class, args) {
// private field
var been_fed = false;
// call super's constructor
var operator = super_class.call(args);
// inherit parent's protected members
var parent = super_class.fetch();
// override a protected method
parent.noise = function() {
return 'bark!';
};
// override a public method
operator.feed = function() {
been_fed = true;
parent.weight += 5;
};
// extend a public method
var super_weigh = operator.weigh;
operator.weigh = function() {
super_weigh();
if(been_fed) console.log('\t'+args[0]+' has been eating :)');
else console.log('\t'+args[0]+' has not been fed yet');
};
// override another public method
operator.toString = function() {
return '{Dog}';
},
// return the operator (interfacable instance object)
return operator;
});
// handle calls to: `Dog()`
namespace.Dog = function() {
// called with new operator: `new Dog()`
if(this !== namespace) {
return constructor.apply(this, arguments);
}
// static call: `Dog()`
else {
// we do no allow extending class `Dog`
return false;
}
};
})(global_namespace);
So now, we can do this:
var giraffe = new Animal('Mr. Giraffe', 720);
giraffe.speak(); // "Mr. Giraffe says nothing"
giraffe.weigh(); // "Mr. Giraffe weighs 720 lbs"
var buddy = new Dog('Buddy', 50);
buddy.speak(); // "Buddy says bark!"
buddy.weigh(); // "Buddy weighs 50 lbs"
// "Buddy has not been fed yet"
buddy.feed();
buddy.weigh(); // "Buddy weighs 55 lbs"
// "Buddy has been eating :)"
This allows private, protected and public fields/functions. Both protected and public field/functions may be overwritten and extended.
console.log(giraffe); // "{Animal}"
console.log(buddy); // "{Dog}"
I have been working on another interesting javascript project and implemented something that may be closer to what you are looking for.
Implement.js
Interested in you thoughts.
Imagine the following situation:
Assembly A is starting the program. (it has a main method)
it loads Assembly B via reflection and instantiates a class of Assembly B.
in this instance a method is called where i would like to get to the Assembly B.
i have already tried
System.Reflection.Assembly.GetCallingAssembly();
System.Reflection.Assembly.GetExecutingAssembly();
but they always give me Assembly A instead of B.
Try getting type of class contain the method you are going for and get its assembly.
string assemblyName = this.GetType().Assembly.FullName;
The Assembly.GetExecutingAssembly() is the proper method to use.
You leave preciously few breadcrumbs to diagnose the cause of having trouble with it. There are however strings attached to this. An important job performed by the jitter is to make methods disappear. This is an optimization called "inlining". In effect, the call to the method is replaced by the code of the method. It is a very important optimization, it for example makes properties as cheap as using public fields. But a consequence it that you'll get the assembly of the calling method. In your case Main(). So you'll see assembly A and not B.
This is not something you ought to tinker with, avoid having a need for this. A method shouldn't be puzzled about what assembly it lives in, you could for example use the typeof(T).Assembly property where T is the class in which the method lives.
You can disable the inlining optimization, you do so with an attribute:
using System.Runtime.CompilerServices;
...
[MethodImpl(MethodImplOptions.NoInlining)]
public void Foo() { }
try this sample ,
public static object ExecuteAssemblyMethod(string methodName,Type assemblyObj, object[] arguments)
{
object result = null;
try
{
object ibaseObject = Activator.CreateInstance(assemblyObj);
result = assemblyObj.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, ibaseObject, arguments);
}
catch (ReflectionTypeLoadException emx)
{
result = null;
return result;
}
catch (Exception ex)
{
result = null;
return result;
}
return result;
}
Usage:-
Assembly assemb = Assembly.LoadFile(#"D:\TEMP\TestClassLibrary_new.dll");
Type testType = assemb.GetType("TestClassLibrary.Class1");
object[] param = new object[] {"akshay" };
object result = LoadAssembly.ExecuteAssemblyMethod("GetName", testType, param);
I am looping thru the ObjectStateEntry of EF so I can access enrty.Entity, I am doing some static validation on the poco classes and i want to also do business rule validation so i created a library to do that, now i have this line of code that expect a type excample Customer..
MyEntityValidator<needtypehere> ev = new MyEntityValidator<needtyehere>(new EntityValidator());
so I am having problem passing type where i mentiened 'needtypehere'. I tried entry.Entity.GetType() but not working . Again this is the signiture of the method
GetErrors(this ObjectStateEntry entry)
To invoke generics from a Type instance, you would have to use:
Type closedType = typeof(MyEntityValidator<>)
.MakeGenericType(entry.Entity.GetType());
object obj = Activator.CreateInstance(closedType);
which is... awkward - as you then need to do lots of additional work with reflection. Alternatively, you can call into a generic method that does the code:
public static void InvokeGeneric<T>(...) {
MyEntityValidator<T> ev = new MyEntityValidator<T>(
new EntityValidator());
... etc; lots more code that uses ev
}
...
typeof(ContainingType).GetMethod("InvokeGeneric").MakeGenericMethod(
entry.Entity.GetType()).Invoke(null, args);
You can use MakeGenericType.