Can execute Code Dynamically in monotouch? - c#

In C# .net we can run code dynamically by using System.Codedom.Provider. Like the same is there any possibility to execute the code dynamically in Monotouch (iPhone/iPad).
Thanks in advance,

Not possible. First because the limitation in how Xamarin.iOS actually works (it doesn't run like a regular .NET apps, but instead compiled to a plain iOS app) and because the security model in Apple Appstore. After all, you can't declare an app to be safe or regulation conforming if the behavior could change anytime.

Since Xamarin.iOS version 7.2 there is some basic support for C#'s dynamic feature. From the release notes:
Experimental:
C# dynamic support. We made it possible to use C# dynamic with Xamarin.iOS but the feature is very complex and we need early adopters let us know what dynamic code they run on other platforms or would like to run on Xamarin.iOS.
I've successfully compiled and executed dynamic access of anonymous types:
dynamic d = new { name = "x" };
tmp = d.name;
Currently you need to add a Microsoft.CSharp.dll as a dependency -- otherwise you'll get an exception similar to this:
Error CS0518: The predefined type `Microsoft.CSharp.RuntimeBinder.Binder' is not defined or imported (CS0518) (DynamicSupportOniOS)
Error CS1969: Dynamic operation cannot be compiled without `Microsoft.CSharp.dll' assembly reference (CS1969) (DynamicSupportOniOS)
Unfortunately neither ExpandoObject nor Json.Net's JObject work right now:
dynamic x = new ExpandoObject();
x.NewProp = "demo"; // this still works
Console.WriteLine(x.NewProp); // fails with Xamarin.iOS 7.2
dynamic d = JObject.Parse("{number:1000, str:'string', array: [1,2,3,4,5,6]}");
Console.WriteLine(d.number); // fails with Xamarin.iOS 7.2
I've created two bug reports for this: https://bugzilla.xamarin.com/show_bug.cgi?id=20081 and https://bugzilla.xamarin.com/show_bug.cgi?id=20082.

Related

C# conditional reference in solution

I am developing a C# application which uses a .tlb file as reference in its solution, which should be installed by another application - however I've recently discovered such use cases, where this other application would not be installed. In these cases my program fails to run correctly, my installer (made with Microsoft Installer Projects) throws the following error:
I suspect the behavior above is due to an initializer subclass which is called by the installer. I want this initializer class only call the discussed .tlb as reference, if it is actually useable/installed - so in case it's actually there, since it is only related to that other application which would install it to the user computer. How can I achieve this "conditional referencing" in my initializer.cs?
The exact code part:
using NGOptMan // This should be conditional or the line actually using it;
...
var optMan = (IOptionsManager)Activator.
CreateInstance(Type.GetTypeFromProgID("SIDEXISNG.OptionsManager"));
// This is the only command where I would use this .tlb.
You can make use of dynamic which allows you to utilise COM objects but without a type library.
Change:
var optMan = (IOptionsManager)Activator.CreateInstance(...)
to
dynamic foo = Activator.
CreateInstance(Type.GetTypeFromProgID("SIDEXISNG.OptionsManager"));
if (foo == null)
return; // failed
// Success
var optMan = (IOptionsManager)foo; // Now cast using the typelib
NOTE the use of dynamic and the removal of the cast.

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.

C# Assembly Loading and Late Binding

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.

Issues with embedding IronPython 2 in a C# web application

First Some Background (incase it helps):
My application is a Web-based framework recently upgraded to v3.5 of the .Net Framework but does not use a Master Pages / User Controls system. It's more akin to the MVC pattern (although much older) and outputs pure HTML down the response stream from Templates. The Python expressions allow some rules and template variations to be achieved.
The old way
When embedding the IronPython 1.x engine in C#, we were able to do code such as:
PythonEngine pe = new PythonEngine();
Assembly a = Assembly.LoadFile("path to assembly");
pe.LoadAssembly(a);
pe.Import("Script");
there is no Import() method in ipy 2.0 and the ImportModule() method doesn't seem to work the same way. The Import() alleviated the need to put a line in every python script we write, such as:
from MyAssembly import MyClass
the fact that MyClass is full of static methods, means that calls to MyClass.MyMethod() work really well. I can't just instansiate an object and assign it to a variable in scope as the assembly that MyClass is contained in is dynamically loaded at runtime.
Now to the issue
I have sorted out all the other parts of the integration of IronPython 2.0 but would prefer not to require my implementers to type "from MyAssembly import MyClass" at the top of every script they write (just seems silly when it was not necessary in ipy 1.x) and likely to be a support issue for a while too.
And finally the question
Has anyone had this issue and resolved it? Am I doing things the wrong way for the DLR? or am I missing something obvious?
I'm not sure of the detail required for someone to help, but I hope this is enough.
Once the assembly's loaded, you can execute the import in the Scope you're using to run the script:
ScriptEngine engine = Python.CreateEngine();
engine.Runtime.LoadAssembly(a);
string code = "from MyAssembly import MyClass";
ScriptSource source = engine.CreateScriptSourceFromString(code, "<import>", SourceCodeKind.Statements);
CompiledCode c = source.Compile();
Scope scope = engine.CreateScope();
c.Execute(scope);
// then run your script in the same scope
We do something similar in our product.
(Hopefully this is valid C# - I actually tried it in IronPython itself, because it was more convenient.)
Thanks Wilberforce,
In the end I did the following:
Assembly a = Assembly.LoadFile("path to assembly");
object var = a.CreateInstance("MyNamespace.MyClass");
Scope.SetVariable("MyClass", var);
This made an object of my class in C# and then passed it to the IronPython scope as a variable.
Note, that this is creating the object in the C# scope (AppDomain) and just passing it to the IronPython. This seems (so far) to work for my problem because the object I am passing is full of only static methods but may not work for a class with state.

Categories