Scripting .NET objects - c#

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).

Related

Is there an object that contains the parameters of a function?

In a method that is so long that it scrolls off the screen. Just to make life easier as I program, if I want to refer to the variables of a class I can use the Me or this objects depending on which language I am using.
eg. Me.var1 = "Hello"
Is there an object (like Me) that would allow easy reference to the parameters of a function?
eg. params.par1 = "World"
There's no such feature in the language. Local variables and method arguments are treated specially by the .NET jitter, they are heavily optimized at runtime. Anything .NET would do, or you would do, to capture those variables would defeat such optimizations.
A very simple solution is to use Window + Split, it gives you two views on your code. Scroll the top one to the method header, write your code in the bottom one. You can adjust the splitter to give you more room in the bottom window.
Taking advantage of IntelliSense would be another way. Prefix the argument names with a little string, like "par". Then typing "par" in your code automatically gives you the list of argument names in the IntelliSense popup window.
These are however but band-aids for the real problem. As soon as you find yourself reaching like this, your first thought should be to split up the code in the function to make it smaller. There are some hard truths I discovered after thirty years of coding:
Long methods have more bugs. There's a metric for this, called "cyclomatic complexity". The higher the number, the more likely that the code is broken. Well supported by Visual Studio, this blog post is useful.
Code should never be indented more than 3 levels deep. By far the simplest way to discover that your cyclomatic complexity is getting out of hand without running a tool.
A method should never be larger than what fits on the screen. Any code that doesn't fit is a cognitive tax that produces compile errors and bugs. There's a corollary to this, programmers with big monitors create more bugs. The hard rule I use is one inspired by using DOS editors, a method should not have more than 25 lines of code.
Wide code produces a special kind of bug, the nasty kind that you can't see. Anything that's off the screen to the right is code that may have a bug that can take you a long time to discover. VB.NET is especially prone to this kind of bug since it uses end-of-line as a statement terminator. Much improved in VS2010 btw, the underscore is now optional in many cases. Always break your line to avoid this kind of bug.
Plan ahead and write maintainable code. Maintained code is never smaller than the original. If you already have trouble writing the original code then by definition you cannot maintain it. You have to start out small.
Always design first, code later. Long methods are a strong indicator of not thinking about code long enough before you start coding. In itself a strong bug inducer, in addition to writing correct code that just doesn't do the job.
The short answer is no. It seems like you are hoping to use this to distinguish between parameter scope and class scope for function parameters and fields with the same name, unfortunately you can't. Either use different naming schemes, or do the following:
public class MyClass {
private string myString;
private int myInt;
public MyClass(string myString) {
this.myString = myString;
}
public int DoStuff(int myInt) {
this.myInt += myInt;
return this.myInt;
}
}
to be really clear and avoid problems, you could change the names:
public class MyClass {
private string m_myString;
private int m_myInt;
public MyClass(string myString) {
m_myString = myString;
}
public int DoStuff(int myInt) {
m_myInt += myInt;
return m_myInt;
}
}
And you should really start by writing a test before the code, then you can check that you haven't accidentally mixed things up in your code.
Footnote
I include this as people coming to the title of this question may be looking for the following information.
While you say
Just for ease of programming - if I am a long way down in a function I would like to see what parameters there are without having to scroll up
In case you really want to look at your parameters from inside your code for other reasons then you need reflection. This is slow, and it's typical use would be to find a method, then reflect the parameters in that method. For a very comprehensive sample, see MSDN - ParameterInfo Class. The pertinent part of the code is:
foreach (MemberInfo mi in typeof(MyClass).GetMembers() )
{
// If the member is a method, display information about its parameters.
if (mi.MemberType==MemberTypes.Method)
{
foreach ( ParameterInfo pi in ((MethodInfo) mi).GetParameters() )
{
Console.WriteLine("Parameter: Type={0}, Name={1}", pi.ParameterType, pi.Name);
}
}
You should be able to use GetParameters() reflection method
MethodInfo barMI = bar.GetMethod("Foo");
ParameterInfo[] pars = barMI.GetParameters();
foreach (ParameterInfo p in pars)
{
Console.WriteLine(p.Name);
}
You can use this in run time. But for your aim, I would try to refactor the number of functions and their names. I try to keep code length under 80 symbols per line and the number of lines in a class under 100. Which is not always possible, but it's a good objective to decouple stuff and keep classes simple.
A simple way would be to encapsulate your parameters in an object so you can just refer to that, and intellitype (or whatever predictive feature) would show you what properties you have available without having to scroll back up. Like this
public class MyParamObject{
public string FirstParam {get;set;}
public string SecondParam {get;set;}
}
Then you could change your method from
public void MyReallyOvergrownMethod(string firstParam, string secondParam){...
to
public void MyReallyOvergrownMethod(MyParamObject params){...
then you can use the params parameter like this in the method
//Deep inside the method
if(params.FirstParam == "SomeValue"{//Do something
This is a numpty solution to a problem that would be best solved by refactoring your method. Look at loops, and conditionals and get them out into seperate private methods that are named after what they do. Loads of stuff on this, if you search for cleancoders.
In light of your comment "Just for ease of programming - if I am a long way down in a function I would like to see what parameters there are without having to scroll up": in Visual Studio, with code showing, just above the scrollbar there is a little bit you can grab and pull down to split the window. You can then have your function declaration visible in one pane and scroll as much as you like in the other. Or you can use Window menu->Split.

Is it good practice to cast objects to dynamic so the correct overloaded method is called?

My question is about whether what follows is an appropriate use of the dynamic keyword in C# 4.
I have some helper methods that provide a more useful representation of various objects than their standard ToString methods do, which I use for unit testing. Here is a simplified example:
public static string PrettyPrint<T>(IEnumerable<T> list)
{
return string.Join(", ", list);
}
// Needed because string is IEnumerable<char>, to prevent
// "Hello" -> "H, e, l, l, o"
public static string PrettyPrint(string s)
{
return s;
}
public static string PrettyPrint(object o)
{
return o.ToString();
}
I use them something like this:
public static void PrettyPrinting()
{
object[] things = { 1, "Hello", new int[] {1, 2, 3} };
foreach (dynamic item in things)
{
Console.WriteLine(PrettyPrint(item));
}
}
This produces the following output:
1
Hello
1, 2, 3
Notice that if I replace the dynamic keyword with object, I get the following (all the calls are routed through PrettyPrint(object)), which is what I am trying to avoid:
1
Hello
System.Int32[]
So my question is essentially is this a code smell or is it legitimate to cast an object to dynamic in this way?
So long as you don't abuse it, duck typing like this is part of the reason dynamic was added to the language.
As to your question, I'm not 100% sure as I don't know your teams style of coding. (I also see little comments ;) )
DuckTyping has it's uses - however a developer needs to know what they're doing before using it. Otherwise it's like running with scissors; it could be abused like other keywords in the C# system.
Personally, I'd rather see extension methods, but depending on the developer, his/her arguments and the documentation done I'd probably allow it.
The biggest reason for my hesitation (and this example is pretty tame to some of the ones I've seen online) is it stops you from finding issues at compile time. It requires more QA testing, a lot more boundary testing, and has a higher risk of failure.
Not an answer to the exact question, but I would say your code is not very OO, which is another smell.
Ideally you want to call item.PrettyPrint() and each item is supposed to return its representation, and override PrettyPrint.
Luckily, existing types can be extended with extension methods. They enable you to add the methods and that's what I would do instead.
If you still want to have the logic for the display of each type in one class, I would combine extension methods with the visitor pattern.
That said, I don't have C# environment so I can't test what I propose. Let me know if you try this, and if it works.

Calling C# methods dynamically based on data from database

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.

Are there any practical examples of tuples for beginning programmers?

I am making an instructional video for C# 4.0 for beginning programmers.
For every topic I introduce I include a practical example which the student could actually use, for instance, for the improved COM Interop functionality, I show how to create an Excel file and fill it with values from code.
For named and option parameters I show how you can create a logging method with 5 parameters but don't have to pass any if you don't want since they all have default values. So they see how calling methods is easier with this feature.
I would also like to introduce tuples as well if I can, but it seems that all the "practical examples" (as in this question: Practical example where Tuple can be used in .Net 4.0?) are very advanced. The learners that use the video learn OOP, LINQ, using generics, etc. but e.g. functional programming or "solving Problem 11 of Project Euler" are beyond the scope of this video.
Can anyone think of an example where tuples would actually be useful to a beginning programmer or some example where they could at least understand how they could be used by and advanced programmer? Their mechanics are quite straight-forward for a beginning programmer to grasp, I would just like to find an example so that the learner could actually use them for a practical reason. Any ideas?
Here's what I have so far, but it is just dry mechanics without any functionality:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//two ways to define them
var customer = new Tuple<int, string, string>(23, "Sam", "Smith");
var customer2 = Tuple.Create<int, string, string>(34, "James", "Allard");
//with type inference, more concise (only available with the Create keyword)
var customer3 = Tuple.Create(23, "John", "Hoopes");
//you can go up to eight, then you have to send in another tuple
var customer4 = Tuple.Create(1, 2, 3, 4, 5, 6, 7, Tuple.Create(8, 9, 10));
Console.WriteLine(customer.Item1);
Console.WriteLine(customer2.Item2);
Console.WriteLine(customer3.Item3);
Console.WriteLine(customer4.Rest.Item1.Item3);
Console.ReadLine();
}
}
}
Tuples are not necessarily the first topic I would tackle for beginner programmers ... however, there are some simple examples.
One that comes to mind is returning a value (which may actually be null) from a function that performs a search (or calculation), together with a boolean that indicates whether the result was found or not. It's an approach that avoids using out parameters, which can be cumbersome or problematic in certain scenarios (like LINQ queries):
public Tuple<string,bool> SearchDictionary( string searchKey )
{
string value;
bool wasFound = someDictionary.TryGetValue( searchKey, out value );
return new Tuple<string,bool( value, wasFound );
}
// since <null> is a legal value to store in the dictionary, we cannot
// use it to distinguish between 'value not found' and 'value is null'.
// the Tuple<string,bool>, however, does allow us to do so...
var result = SearchDictionary( "somekey" );
if( result.Item2 )
{
Console.WriteLine( result.Item1 );
}
Another example that I think is natural, is creating associations between two values without creating an explicit class for the purpose. For example, let's imagine we want to represent pairs of opponents who will play tennis matches. We could use:
// note the symmetry in the representation of opponents of a tennis match...
// if the relationship were asymmetrical, tuple may not be the best choice.
var playerA = new TennisPlayer("Serena Williams");
var playerB = new TennisPlayer("Venessa Williams");
var match = new Tuple<TennisPlayer,TennisPlayer>( playerA, playerB );
Creating a class for something like this can be avoided by using tuples instead.
A final example, is using tuples to represent composite keys in a dictionary. Since Tuple<>s can be compared to one another for equality, it becomes possible to do stuff like:
var complexDictionary =
new Dictionary<Tuple<string,int,decimal,DateTime>,string>();
complexDictionary.Add( new Tuple("USA",-4,1.671,DateTime.Now), "active" );
EDIT: One comment I would make when educating developers about the use of tuples, is that tuples should rarely (if ever) appear in the public interface of code you expect others to consume. As tools to simplify the internal implementation of a class or module, I think they're fine. But once you start passing them in or out of methods that developers consuming your code have to interact with, you run in the problem that tuples obscure the semantics of your API. It becomes hard for developers to interpret what Tuple<int,int> is supposed to mean. What do Item1 or Item2 mean in such a case? When you see yourself needing to pass tuples in or out of methods, you should strongly consider writing a class to encapsulate and clarify the relationship.
The best practical reason i can see is using them as temporary "classes". You want to associate multiple pieces of information, but not create yet another class structure to hold them.
They should be temporary, because if you're using them a lot, you should be going all the way and properly creating classes...
I can't think of a good specific example, i've mostly used them for small things, like temporary maps that need a single key but multiple pieces of information in the value...
I use them in place of private classes. The are great when used internally in a class.
Exposing them outside the class only led to confusion. I kept having to open the class to determine what was what.
What about on a login form? They see those all of the time.
var loginCredentials =
new Tuple<string, SecureString>(nameTextBox.Text, passwordTextBox.Text);
if (Login(loginCredentials))
Console.Writeline("Login - Success!");
else
Console.Writeline("Login - Failure");
...
public bool Login(Tuple<string, SecureString> loginCredentials)
{
return ...
}

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