Accessing class and function after compiling ( CompiledAssembly ) - system-codedom-compiler

Heres some example code. I successfully figured out how to compile this. I grabbed the location and was able to use visual studios object browser to look through the DLL. I cant figure out how to get a class instance and call a function.
public static void test()
{
JScriptCodeProvider js = new JScriptCodeProvider();
System.CodeDom.Compiler.CompilerParameters param = new System.CodeDom.Compiler.CompilerParameters();
var cr = js.CompileAssemblyFromSource(param, new string[] { "package pkg { class b { public function increment(x) { return x+1; } } }" });
foreach (var e in cr.Errors) {
var s = e.ToString();
}
var asm = cr.CompiledAssembly;
var module = cr.CompiledAssembly.GetModules();
//or var module = cr.CompiledAssembly.GetModule("JScript Module");
//...
}

Hmmm realy late on the answer but this is how you would invoke a method from a CodeDom compiled class
You have to use reflection to create an assembly from your compiler results...(your var cr)
Assembly assembly = cr.CompiledAssembly;
Then you have to create an instance of the class you want
object sourceClass = assembly.CreateInstance("YourNamespace.YourClass");
Then you invoke any method inside the class
var result = sourceClass.GetType().InvokeMember("YourMethod", BindingFlags.InvokeMethod, null, sourceClass, new object[] { *Parameters go here* });
And with that what ever the method you invoked had to returned would now be the value of the "result" var....pretty easy.

Related

Unable to access a local variable inside a groovy closure

I'm using java to modify some groovy code using reflection.
The original groovy code is of the form:
void method() {
A(processId);
B();
}
I need to modify this to inject processId:
void callMethod() {
int processId = rand();
invokeMethod(
{->
A(processId);
B();
}, processId);
}
void invokeMethod(Closure closure, int processId) {
doSomething(processId);
closure.call();
}
Note: invokeMethod() is an existing method and is not injected.
When I modified the original code as above, I'm getting this error:
"groovy.lang.MissingPropertyException: No such property: processId"
I've tried setting the variableScope of the "callMethod" method to include the "processId" variable as a DeclaredVariable.
For reference, here is the code I used to do this:
private void wrapMethod(#NonNull MethodNode node)
{
VariableExpression var = new VariableExpression("processId", new ClassNode(Integer.class));
var.setClosureSharedVariable(true);
//Generate a statement that creates a processId
Statement statement = GeneralUtils.declS(var, GeneralUtils.callThisX("getUUID"));
ClosureExpression methodClosure = createMethodClosure(node);
ArgumentListExpression args = createArgumentListExpression(methodClosure,
varX("processId"));
MethodCallExpression method = GeneralUtils.callThisX("invokeMethod", args);
BlockStatement newMethodCode = GeneralUtils.block(statement, GeneralUtils.stmt(method));
newMethodCode.setVariableScope(methodClosure.getVariableScope().copy());
//Just to be safe, modifying the scope of the node as well.
VariableScope newScope = node.getVariableScope().copy();
newScope.putDeclaredVariable(var);
node.setCode(newMethodCode);
node.setVariableScope(newScope);
}
private ClosureExpression createMethodClosure(MethodNode node) {
//Get code from within node to dump into a closure.
BlockStatement block = (BlockStatement) node.getCode();
//Setting closureScope and adding processId
VariableScope closureScope = block.getVariableScope().copy();
closureScope.getReferencedLocalVariablesIterator()
.forEachRemaining(x -> x.setClosureSharedVariable(true));
Variable var = new VariableExpression("processId", new ClassNode(Integer.class));
var.setClosureSharedVariable(true);
closureScope.putDeclaredVariable(var);
ClosureExpression methodClosure = GeneralUtils.closureX(block);
methodClosure.setVariableScope(closureScope);
return methodClosure;
}
I've verified the code to check that 'processId' is accessible within the invokeMethod() block and that the resultant code from the injection is as expected.
Any ideas on why this is not working?

mockito spy doesn't work on android studio

I'm trying to mock some object and manipulate the return value of the object's method. After applying spy or mock, seems manipulating the return value doesn't work. The final result 'res' is not '10' as I expected but '1'. After instantiating class B and call the method getAAA(), it just calls the real method of A.aaa() and returns '1'.
class A {
public int aaa() { return 1; }
}
class B {
A classA;
B(A classA) { this.classA = classA; }
public int getAAA() { return classA.aaa(); }
}
A spyA = mock(A.class);
when(spyA.aaa()).thenReturn(10);
A AA = new A();
int res = new B(AA).getAAA();
Logxx.d("RESULT: " + res);
RESULT: 1
You are not using your mock/ spy instead you are creating new object with new.
Also, you are mocking the object with mock(...) but you are calling you object as spy(spyA). This isn't wrong since it is just a variable name. But not readable.
A mockA = mock(A.class);
when(spyA.aaa()).thenReturn(10);
A AA = new A();
int res = new B(mockA).getAAA();
Logxx.d("RESULT: " + res);

_COMPlusExceptionCode -532462766 While creating ModuleBuilder.DefineType

I am trying to create a class dynamically based on a base class type.
Below is the code which causing problem
TypeBuilder tb = DynamicType.CreateType(DynamicType.modBuilder, typeof(ResultViewModelVersioned).ToString());
The function for create type is as follow
public static TypeBuilder CreateType(ModuleBuilder modBuilder, string typeName)
{
TypeBuilder typeBuilder = modBuilder.DefineType(typeName,
TypeAttributes.Public );
return typeBuilder;
}
But i am getting com exception _COMPlusExceptionCode -532462766 while defining type in above function.
Here is my function which creates dynamic object
public object GetViewModel<TresultType, TviewModelType>(TresultType result, TviewModelType ViewModel)
{
if (DynamicType.asmBuilder == null)
DynamicType.GenerateAssemblyAndModule();
var finalType = DynamicType.modBuilder.GetType("Beacon11");
TypeBuilder tb = DynamicType.CreateType(DynamicType.modBuilder, ViewModel.GetType().ToString());
tb.SetParent(typeof(ResultViewModelVersionable));
var sourceType = result.GetType();
var targetType = tb.GetType();
foreach (var property in sourceType.GetProperties())
{
var targetProperty = targetType.GetProperty(property.Name);
if (targetProperty == null)
{
DynamicType.CreateProperty(tb, property.Name, property.GetType());
}
}
finalType = tb.CreateType();
var Methods = tb.GetMethods();
Object obj = Activator.CreateInstance(finalType);
return obj;
}
I got code to create DynamicType From the below link
http://geekswithblogs.net/rgupta/archive/2008/12/01/dynamically-creating-types-using-reflection-and-setting-properties-using-reflection.emit.aspx
Any help would be greatly appreciated. If you need any further information please let me know.

Exports whole object with functions

i tried found answer in stackoverflow and can't find any answer about this
i just started learning NodeJS . and i got a question, is there any way how can i exports whole object with his functions or i can exports only functions of object?
thanks for advice!
when i try it i got error like this
TypeError: object is not a function
i got simple code like this :
animal.js
var Animal = {
name : null,
setName : function(name) {
this.name = name;
},
getName : function() {
console.log("name of animal is " + this.name);
}
}
exports.Animal = Animal;
and server.js
var animal = require('./animal');
var ani = new animal.Animal();
The error is because new expects a Function while Animal is a plain Object.
Though, with the Object, you could use Object.create() to create instances:
// ...
var ani = Object.create(animal.Animal);
Otherwise, you'll have to define Animal as a constructor Function:
function Animal() {
this.name = null;
// ...
}
exports.Animal = Animal;
Note: Depending on precisely what you want to accomplish, Functions are a type of Object and can hold additional properties.
function Animal(name) {
this.name = name || Animal.defaultName;
}
Animal.defaultName = null;

Orchard CMS- Get the current Data Migration Record version number

Given the name of a Migrations class as a string, how can I get the current version number as stored in Orchard_Framework_DataMigrationRecord?
I can see Version in IExtensionManager, but that appears to just be the module version as defined in module.txt.
OK, so I've solved this myself-
I knew that Orchard must already be executing similar code to what I require when it fires off migration methods, so I created a new migrations file, and put a breakpoint on the Create() method. When the breakpoint hit, I looked up through the call stack to find DataMigrationManager in Orchard.Data.Migration. Everything I needed was in there, and if anyone else has similar requirements, I suggest they have a look at that class as a starting point.
This is pretty much lifted straight out of that class:
string moduleName="Your.Module.Name";
var migrations = GetDataMigrations(moduleName);
// apply update methods to each migration class for the module
var current = 0;
foreach (var migration in migrations)
{
// copy the objet for the Linq query
var tempMigration = migration;
// get current version for this migration
var dataMigrationRecord = GetDataMigrationRecord(tempMigration);
if (dataMigrationRecord != null)
{
current = dataMigrationRecord.Version.Value;
}
// do we need to call Create() ?
if (current == 0)
{
// try to resolve a Create method
var createMethod = GetCreateMethod(migration);
if (createMethod != null)
{
//create method has been written, but not executed!
current = (int)createMethod.Invoke(migration, new object[0]);
}
}
}
Context.Output.WriteLine("Version: {0}", current);
A couple of methods you may need:
private DataMigrationRecord GetDataMigrationRecord(IDataMigration tempMigration)
{
return _dataMigrationRepository.Table
.Where(dm => dm.DataMigrationClass == tempMigration.GetType().FullName)
.FirstOrDefault();
}
private static MethodInfo GetCreateMethod(IDataMigration dataMigration)
{
var methodInfo = dataMigration.GetType().GetMethod("Create", BindingFlags.Public | BindingFlags.Instance);
if (methodInfo != null && methodInfo.ReturnType == typeof(int))
{
return methodInfo;
}
return null;
}
Don't forget to inject any dependencies that you may need.

Resources