Calling C# methods dynamically based on data from database - c#

My boss has asked me to look into a calculation engine. Effectively, the user will have a table of data that can have calculations be performed on. They will also be able to build their own calculations based on certain restrictions we enforce (the built calculations will then be stored in the database)
Is it possible to call a specific method in C#, dependent upon what is stored in the database? So if the database says, a calculation should perform a standard deviation. When we get that information from the database, is it then possible to call a standard deviation method that we will have in C#?
I hope this is clear.

Considering the small/known amount of operations which will be executed on your data, I would opt to manually code these operations, based on the data retrieved from the database. For extendability/maintainability, it's best to create a proper design for this instead of using a simple switch statement. I'm guessing the Strategy pattern will suit your needs.
As others stated, you could use reflection, to call the methods as specified in the database. The problem with this approach is the data in your database is strongly linked to the method signatures. This is less maintainable than the first approach, but does allow for great extendability with minimal code adjustments. Another downside is using MethodInfo.Invoke() is rather slow.
If you would opt for reflection, but find the Invoke() approach to be too slow, I can recommend this article by Jon Skeet which explains how to convert a MethodInfo into a delegate instance. This gives a major speed boost. I wrote a generic implementation using expression trees for this recently.
All in all, it seems like option 1 is still the best for your purposes.

Yes, this is possible; it's called reflection and it's a standard C# feature. Many tutorials exist out on the web; here's some pretty simple example code:
using System;
using System.Reflection;
class CallMethodByName
{
string name;
CallMethodByName (string name)
{
this.name = name;
}
public void DisplayName() // method to call by name
{
Console.WriteLine (name); // prove we called it
}
static void Main()
{
// Instantiate this class
CallMethodByName cmbn = new CallMethodByName ("CSO");
// Get the desired method by name: DisplayName
MethodInfo methodInfo =
typeof (CallMethodByName).GetMethod ("DisplayName");
// Use the instance to call the method without arguments
methodInfo.Invoke (cmbn, null);
}
}
http://en.csharp-online.net/CSharp_FAQ:_How_call_a_method_using_a_name_string

You can store operations in DB and use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly.
See sample here: Execute code at runtime

Yes, you can do it using Reflection. You could write a class that contains all the operations that user could do and then call its methods dynamically.
public static class UserOperations
{
public static decimal Average(IEnumerable<decimal> source)
{
return source.Average();
}
// Other methods
}
class Program
{
static void Main(string[] args)
{
// The operation retrieved from the db
string operation = "Average";
// The items on which the operations should be performed
decimal[] items = { 22m, 55m, 77m };
object result = typeof(UserOperations).GetMethod(operation).Invoke(null, new object[] { items });
Console.WriteLine(result);
Console.ReadLine();
}
}

I would suggest you implement strategy pattern (http://www.dofactory.com/Patterns/PatternStrategy.aspx)
You can load different strategies (algorithms) for different calculations required.
There is a nice post as well http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/22/applying-strategy-pattern-instead-of-using-switch-statements.aspx

You can use the switch statement in C# to execute the operation you want depending on the value of your record's field (or scalar) coming from the database. This is OK if you have a small/limited number of supported operations, otherwise of course you could use reflection and the MethodInfo class to invoke a member method by "string name" on a certain class.

Related

Overhead of delegate definition inside of another method

I'm curious to understand what's happening behind the scenes in a situation like this:
public static void OuterMethod() {
// some random code
var a = 42;
var b = "meaning of life";
Func<string, object> factory = (aString) {
// do something with a and b
return "Hello World";
};
// some more random code
factory("My string");
}
I'm particularly interested in cases where OuterMethod is called very often. In my case it's the MVC request pipeline where OuterMethod is called once for each request.
Am I incurring a lot overhead by having to build factory each time the method is called? I could easily move the Func outside of OuterMethod into its own static method however in my actual scenario because it is defined inside I have access to a lot of variables I need to do my calculation that I would otherwise need to include in the signature of a method defined outside. Maybe this is just a micro optimization but I would like to better understand how the compiler treats these kinds of statements.
The actual lambda is going to result in a new named method (you just don't know what that name is) being created at compile time (the exact semantics will vary based on some of the specifics).
The only work being done on each invocation of the method is the creation of a new delegate object that has its own pointer to the same named method. If constructing that one object instance is really too much for you (hint: its not) then you could save that work by extracting the delegate out of the method.

How can I allow a class to be declared to use either floats or doubles?

Sorry if the title is poorly worded. Let's say I have a ray tracer and I want there to be the ability to use either floats or doubles. How can I make it possible to declare a new instance of the class choosing either floats or doubles? I don't want to create two classes and call one double and the other single.
There is not a clean way to handle this in .NET. Generics do not support arithmetic operations directly. You can solve this via workarounds such as MiscUtils or via the creation of a separate calculator class and delegating the math to it, but this often makes the code more complex than having two implementations.
You could use dynamic here internally, which would work as well. However, this will add a (slight) overhead, which may mitigate the usefulness of this. If performance is the main reason you don't want to only support double-precision math, then using dynamic is probably not an option.
One option would be to use T4 to create a template that builds both versions of the code from a single source file. This would provide you full, native support without overhead (it's essentially just writing the two classes for you).
You can use C# generics for this:
using System;
class Test<T>
{
T _value;
public Test(T t)
{
// The field has the same type as the parameter.
this._value = t;
}
public void Write()
{
Console.WriteLine(this._value);
}
}
class Program
{
static void Main()
{
// Use the generic type Test with an int type parameter.
Test<int> test1 = new Test<int>(5);
// Call the Write method.
test1.Write();
// Use the generic type Test with a string type parameter.
Test<string> test2 = new Test<string>("cat");
test2.Write();
}
}
This blog describes it in a bit more detail for you http://www.dotnetperls.com/generic

Efficient use of reflection in C#

I'm writing a library in C# that I will later use for an application, and I want the library to be as efficient as sanely possible (ie. don't over-complicate things too much to make it more efficient). However, I have this question about how to most efficiently use reflection on a class/methods and to illustrate the question I've simplified my class a lot down to this:
class MyClass
{
private static Dictionary<string, object> methods;
public void Method1()
{
// Do something.
}
public void Method2()
{
// Do something else.
}
}
Now, what I want is from within the class (a private method yet to be created), take a string containing the method-name, then fire the method, simple as that. The easiest way of doing this would be to just look at the name, get a method with that name, and execute it, but that forces me to use reflection a lot of times. This private method can potentially be called thousands or tens of thousands of times, and it need to be quick. So I came up with two possible solutions. As you can probably see I've added a static dictionary containing string->object (replacing object with actual type, just wrote object cause that works with both my examples). Then I'd add a static constructor that goes trough the class and adds all the methodinfos to the methods-dictionary. And then comes the question, on creation of a new instance of the class, should I create bound delegates to the methods and put those in a non-static private dict, or should I simply fire the methods using the MethodInfo in the methods-dictionary?
The average use-case will create 10 instances of this class, and have 1000+ calls to the method that should fire either Method1 or Method2 depending on it's string-argument (and no, switch-case is not an option because of the extensibility of the class, as said, this was a simplified version). What would be the most efficient way of achieving this?
Obviously no one can answer the question without actually trying it and doing performance tests to see if your goal is met or not.
Reflection is a lot faster in modern versions of the framework than it used to be, but it still is not as fast as simply invoking a delegate.
My suggestion would be to start with your proposed solution: build the cache of method infos once:
class MyClass
{
static Dictionary<string, MethodInfo> cache = new ...
public void InvokeByName(string name)
{
MethodInfo methodInfo = GetMethodInfoFromCache(name);
methodInfo.Invoke(this, new object[] {});
}
When asked to invoke a method identified by a string on a particular instance as the receiver, look up the method info by name and then invoke it with the given receiver. Measure the performance of that and see if it meets your goal. If it does, great; don't waste any more of your valuable time trying to make something faster that is already fast enough.
If that is not fast enough then here's what I'd do:
class MyClass
{
static Dictionary<string, Action<MyClass>> cache = new ...
public void InvokeByName(string name)
{
GetActionFromCache(name).Invoke(this);
}
So what does GetActionFromCache do? If there is already an action in the cache, we're done. If there is not, then obtain the MethodInfo via Reflection. Then use the Expression Tree library to build up a Lambda:
var methodInfo = SomehowGetTheMethodInfo(name);
// We're going to build the lambda (MyType p)=>p.<named method here>()
var p = Expression.Parameter(typeof(MyType), "p"));
var call = Expression.Call(p, methodInfo);
var lambda = Expression.Lambda<Action<MyType>>(call, p);
var action = lambda.Compile();
And now you have an action in hand that you can invoke with the instance. Stick that thing in the cache.
This is, incidentally, at an incredibly simplified level, how "dynamic" works in C# 4. Our problem is enormously complicated by the fact that we have to deal with the receiver and arguments being of any type. You have it very easy comparatively.
Since you will obtain all of the MethodInfo instances and the name to map them to (presumably through the MethodInfo.Name property, you can go one step further and create a compiled lambda expression in the form of a delegate which you can execute.
First, it's assumed that all of your methods will have the same signature. In this case, it's an Action<T> delegate. With that, your dictionary will look like this:
// No need to have the dictionary **not** readonly
private static readonly IDictionary<string, Action<MyClass>> methods =
new Dictionary<string, Action<MyClass>>;
Then, in your static constructor, you would use reflection to get all of the MethodInfo instances:
static MyClass()
{
// Cycle through all the public instance methods.
// Should filter down to make sure signatures match.
foreach (MethodInfo methodInfo in typeof(MyClass).
GetMethods(BindingFlags.Public | BindingFlags.Instance))
{
// Create the parameter expression.
ParameterExpression parameter = Expression.
Parameter(typeof(MyClass), "mc");
// Call the method.
MethodCallExpression body = Expression.Call(pe, methodInfo);
// Compile into a lambda.
Action<MyClass> action = Expression.Lambda<Action<MyClass>>(
body, parameter).Compile();
// Add to the dictionary.
methods.Add(methodInfo.Name, action);
}
}
Then, your private method would look like this:
private void ExecuteMethod(string method)
{
// Add error handling.
methods[method]();
}
The benefit here is that you get the performance of compiled code, while paying a very small price (IMO) in code complexity (in creating the delegate). Granted, there is a slight overhead in calling the code through a delegate, but that's been vastly improved (it had to be with the introduction of LINQ, since they would be executed many, many times).
If I had the choice here, I would probably go with Henk's suggestion and use dynamic. Method invocations are blazingly fast (much faster than ordinary reflection and almost like normal method calls).
You may also find inspiration by looking at this class, which extends DynamicObject and illustrates how you could do the dynamic invocation of methods.
However, if you wish to support 3.5 or keep your options open and you have no objections to using a 3rd party library, then this can still be fairly easily accomplished:
void Invoke( string methodName )
{
this.CallMethod( methodName );
}
CallMethod creates a DynamicMethod delegate for invoking that particular method and caches it in case you call the same method again. There are also extensions for invoking methods with parameters and a ton of other useful reflection helpers.
If you prefer to cache the delegate yourself (we use a ConcurrentDictionary and WeakReferences to do this, which means it might get garbage collected), just call DelegateForCallMethod instead.
The library supports both 3.5 and 4.0. WP7 does not support Reflection.Emit and therefore cannot use IL generation and DynamicMethod. However, WP 7.5 does support this (but Fasterflect, as the library is called, does not yet support it).
From your comment:
Well, simply put it's connected to a server, the server sends commands in the form of <name> <param1> <param2> ... <paramN>, and the name determines what functionality should be performed. I want to be able to just add functions with matching names (or rather, I've created an attribute that lets me name methods other than their method-name cause command-names might be numeric), cause the list of names is looooong, and I don't want to do a switch-case.
You can solve this problem with a simple command interface and a table-driven factory for a matching instance (or a type, if the command instances are not reusable).
public interface ICommand {
void Execute();
}
public class Processor {
private static Dictionary<string, ICommand> commands;
static Processor() {
// create and populate the table
}
public void ExecuteCommand(string name) {
// some validation...
commands[name].Execute();
}
}
No reflection involved.
To create a new command, just create a new class that implements ICommand and add the corresponding line to the commands table inside the Processor static constructor.
public class FooCommand : ICommand {
public void Execute() {
// foo away!
}
}
...
public class Processor {
static Processor() {
...
commands["foo"] = new FooCommand();
...
}
}
There are many advantages to this design, aside from performace. Your commands are isolated from each other, changes to one command or the creation of new commands won't impact other commands. They're better testable and easier to maintain. Even the processor can be closed (in an OCP way) if you can maintain your table in a config file or a database, for example.
You can certainly find alternative designs and ways to pass parameters to the commands, but I hope this gives you the basic idea.
In this particular case you can declare your dictionary slightly differently and get the result you are after::
class MyClass
{
private static Dictionary<string, Action<MyClass>> methods;
public void Method1()
{
// Do something.
}
public void Method2()
{
// Do something else.
}
static MyClass(){
methods = new Dictionary<string, Action<MyClass>>();
foreach(var method in typeof(MyClass).GetMethods(
BindingFlags.Public | BindingFlags.Instance)
)
{
methods.Add(
method.Name,
Delegate.CreateDelegate(typeof(Action<MyClass>),method)
as Action<MyClass>);
}
}
}
This code has the advantage of not using code generation. However if you have methods of different signatures then a different approach will be needed. Here we are creating open instance delegates. (Note this doesn't always work correctly if MyClass is a struct or if any of these methods are generic virtual methods).
The fastest way of doing something is not to do it at all. Have you considerer just making interface like:
interface ICallMe
{
void CallByName(string name, object args);
}
This way if some of the implemetations wants to be insanely smart it can do reflection+caching+IL generation, the others can simply use if/switch.
Downside - significantly less fun to implement and debug.
Invoking a MethodInfo is slow. So I think creating a new dictionary for each instance should be good enough. Another option is to create a delegate that accepts the instance (Action<MyClass>) using Expressions (and then store them in the static dictionary):
MethodInfo method = typeof(MyClass).GetMethod("Method1");
var parameter = Expression.Parameter(typeof(MyClass));
var call = Expression.Call(parameter, method);
var lambda = Expression.Lambda<Action<MyClass>>(call, parameter);
Action<MyClass> del = lambda.Compile();
Have you considered using Code Generation and T4 Text Templates?
http://msdn.microsoft.com/en-us/library/bb126445.aspx
http://msdn.microsoft.com/en-us/library/bb126478.aspx
Then you could use a case statement.
Something like
partial Class MyClass
{
public void Exec(string funcToExec)
{
swtich(funcToExec)
{
<#
foreach(MethodInfo mi in
typeof(MyClass).GetMethods(BindingFlags.Public | BindingFlags.Static)
{
if(mi.Name != "Exec"){
#>
case : "<#= mi.Name #>"
<#= mi.Name #>();
<#
}}
#>
}
}
}

Scripting .NET objects

I have a simple .NET application which runs as Windows Service.
Say it has one Class
MyClass
{
Run(Destination d)
Walk(Destination d)
Wash(Dishes d)
}
I want to create a console application where I would type simple human readable commands
like
run left
walk right
Pretty much like you do in windows console. I wonder what is the best way to implement this mapping. A straight methods is of course create your own string parser with lots of switch statements but I think if there is better and faster method.
This might be too much for your needs, but I think a robust, flexible way to do it would be creating a couple of meta-data attributes to decorate the classes you might want to call from your shell, something like:
[ScriptableClass]
public class MyClass
{
[ScriptableMethod(typeof (Destination),typeof(int))]
public void Run (Destination f, int distance) {}
}
Then, during your shell's startup, you load your assemblies via reflection and look for types marked with the ScriptableClass attribute. For each of them, you inspect their public methods looking for those marked with the ScriptableMethod attribute, and you can build a dictionary of classes and their scriptable methods (along with info about parameters). For the previous example, you would have a 'MyClass.Run' command you can could from the shell. When received, your scripting engine would create / lookup an instance of the class and execute the method.
The advantage of this method is that you wouldn't have to modify your scripting engine every time you add new classes or modify methods.
You have two options here:
Use reflection to find the class method with the approrpiate name and invoking it.
Use the command pattern, where each command object would have a name and a Run() method. You can easily find the desired command by name, then run it.
UPDATE: Aggreed, there are more than two options (see Guffa's answer). But these two are the ones that make the code clearer IMHO.
Not really. There are other methods, but if they are better is mostly a matter of taste, and for identifying a string you can't do it much faster than a switch.
If all method have the same parameters, you could set up a dictionary of strings and delegates.
Example:
var methods = new Dictionary<string, Action<int>>();
methods.Add("run", n => MyClass.Run(n));
methods.Add("walk", n => MyClass.Walk(n));
methods.Add("wash", n => MyClass.Wash(n));
string cmd = "run";
int param = 42;
if (methods.ContainsKey(cmd)) {
methods[cmd](param);
} else {
Console.WriteLine('Say what, human?');
}
Perhaps a PowerShell CommandLet would be an option, although that would constrain you or your users to PowerShell (which is a superior shell IMO).

Is there an easy way to parse a (lambda expression) string into an Action delegate?

I have a method that alters an "Account" object based on the action delegate passed into it:
public static void AlterAccount(string AccountID, Action<Account> AccountAction) {
Account someAccount = accountRepository.GetAccount(AccountID);
AccountAction.Invoke(someAccount);
someAccount.Save();
}
This works as intended...
AlterAccount("Account1234", a => a.Enabled = false);
...but now what I'd like to try and do is have a method like this:
public static void AlterAccount(string AccountID, string AccountActionText) {
Account someAccount = accountRepository.GetAccount(AccountID);
Action<Account> AccountAction = MagicLibrary.ConvertMagically<Action<Account>>(AccountActionText);
AccountAction.Invoke(someAccount);
someAccount.Save();
}
It can then be used like:
AlterAccount("Account1234", "a => a.Enabled = false");
to disable account "Account1234".
I've had a look at the linq dynamic query library, which seems to do more or less what I want but for Func type delegates, and my knowledge of Expression trees etc isn't quite good enough to work out how to achieve what I want.
Is there an easy way to do what I want, or do I need to learn expressions properly and write a load of code?
(The reason I want to do this is to allow an easy way of bulk updating account objects from a powershell script where the user can specify a lambda expression to perform the changes.)
The Dynamic LINQ library is a fine choice, as it'll generate expressions you can compile to code in a lightweight fashion.
The example you provided actually produces a boolean -- so you should be able to ask for a Func and it might sort it out.
Edit: This of course is wrong, as Expressions don't have assignment in them at all.
So, another potential way is to take two lambdas. One to find the property you want, one to provide a value:
(a => a.AccountId), (a => true)
Then use reflection to set the property referenced in the first lambda with the result of the second one. Hackish, but it's still probably lightweight compared to invoking the C# compiler.
This way you don't have to do much codegen yourself - the expressions you get will contain most everything you need.
You may try this: Dynamic Lambda Expressions Using An Isolated AppDomain
It compiles a lambda expression using CodeDOM compiler. In order to dispose the in-memory assembly that gets created, the compiler runs on an isolated AppDomain. For the passing the expression through the domain boundary, it has to be serialized. Alas, Expression<> is not Serializable. So, a trick has to be used. All the details are explained in the post.
I'm the author of that component, by the way. I would like very much to hear your feedback from it.
There is no general way to parse a string into a lambda expression without a full compilation, because lambda expressions can reference things that are defined outside the lambda expression. I know of no library that handles the specific case you want. There's a long discussion of this on a thread on a C# discussion group.
The easiest way to get what you want is to compile a method at runtime. You can write a function that takes in the string "a.Enabled = true; return a;" and sticks that in the middle of a function that takes an Account as a parameter. I would use this library as a starting point, but you can also use the function mentioned on another thread.
That's easy:
Use CodeDom to generate the module containing the "surrounding class" you'll use to build the expression; this class must implement the interface known to your application
Use CodeSnippedExpression to inject the expression into its member.
Use Activator type to create the instance of this class in runtime.
Basically, you need to build the following class with CodeDom:
using System;
using MyNamespace1;
using ...
using MyNamespace[N];
namespace MyNamespace.GeneratedTypes
{
public class ExpressionContainer[M] : IHasAccountAction
{
public Action<Account> AccountAction {
get {
return [CodeSnippedExpression must be used here];
}
}
}
}
Assuming that IHasAccountAction is:
public IHasAccountAction {
public Action<Account> AccountAction { get; }
}
If this is done, you can get the expression compiled from string with ease. If you need its expression tree representation, use Expression<Action<Account>> instead of Action<Account> in generated type.

Categories