image Note: This is the third article in the series. In the first two articles, I explained

Preface

In this post, we’ll see how to use C# as a scripting language in your .NET applications. Let us start with a very minimal game application, where you have two players, and your users can control these players by writing some script.

In the previous post, I explained how to create a delegate/predicate from Mono’s Evaluator and pass it back to the Main application, so that we can use the predicate for custom filtering operations. Now, What is interesting in below code is, how we are passing the context information from the main application to Mono’s Evaluator, so that the objects from the main applications can be accessed via Mono’s Evaluator for scripting.

C# For Scripting

So here we go. Have a look at this entire implementation first. Fire up a console project in Visual Studio, add a reference to Mono.CSharp.dll (See the first post), and try this code. (You can click ‘Copy to clipboard’ for copying the code from the listing below).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.CSharp;

namespace MonoHost
{
    // A simple extension class with methods to 
    // invoke Evaluator methods on a string
    public static class EvaluatorExtensions
    {
        public static T Eval<T>(this string code) where T : class
        {
            return Evaluator.Evaluate(code) as T;
        }

        public static void Run(this string code, bool repQuotes = false)
        {
            var run = repQuotes ?
                        code.Replace("'", "\"") : code;
            Evaluator.Run(run);
        }
    }

    //A simple player class so that we can create few 
    //player objects later
    public class Player
    {
        public string Name { get; set; }

        public void Attack(Player target)
        {
            Console.WriteLine(Name + " is attacking " + target.Name);
        }

        public void Jump()
        {
           Console.WriteLine(Name + " is jumping");
        }

        public void Goto(int x,int y) 
        { 
           Console.WriteLine(Name + " is going to " + x + "," + y);
        }
    }


    // A Context class to share context between our ScriptDriver and Mono's Evaluator 
    public static class Context
    {
        static Context()
        {
            Items = new Dictionary<string, object>();
        }
        public static Dictionary<string, object> Items { get; set; }
    }


    //Main Program
    class ScriptDriver
    {
        static void Main(string[] args)
        {
            //Initializing the evaluator
            Evaluator.Init(new string[0]);

            //Step 1 - Add this assembly as a reference so that we can access the Context class
            Evaluator.ReferenceAssembly(typeof(ScriptDriver).Assembly);

            //Using evaluator to run some code
            //via our Extension method
            @"using System;
              using System.Linq;
              using MonoHost;
              using System.Collections.Generic;"
                .Run();

            //Step 2 - Adding few items to the Context
            Context.Items.Add("jim", new Player { Name = "Jim" });
            Context.Items.Add("joe", new Player { Name = "Joe" });

            //Step 3 - Retreive the items from the Context in Evaluator
            @"var jim=(Player)Context.Items['jim'];
              var joe=(Player)Context.Items['joe'];"
                 .Run(true);

            Console.WriteLine("<<-- Game Started - Control Jim and Joe. -->>");

            while (true)
            {
                Console.Write("->");
                string input = Console.ReadLine();
                if (input.Equals("@@")) return;
                try { input.Run(); }
                catch (Exception ex) { Console.WriteLine(ex.Message); }
            }
        }
    }

}

There are a couple of simple, but interesting tricks to note in the above code. We have a Context class with a static dictionary inside the same, to pass data back and forth between our main application and the Evaluator.

  • In Step 1, see how are are adding the current assembly as a reference to the Evaluator, so that we can access the Context class.
  • In Step 2, we are filling the context with some instances created in the main application
  • In Step 3, see how we are retrieving the instances in the Evaluator, from the context

Now, as we have our objects exposed to Evaluator, we can use them from the script. Run the application, and have fun with invoking methods of your ‘jim’ and ‘joe’ objects in the script. This is my script console when I run the above program

<<-- Game Started - Control Jim and Joe. Enter @@ to stop -->>
->jim.Attack(joe);
Jim is attacking Joe
->for (int i=0;i<40;i+=5) joe.Goto(20,30+i);
Joe is going to 20,30
Joe is going to 20,35
Joe is going to 20,40
Joe is going to 20,45
Joe is going to 20,50
Joe is going to 20,55
Joe is going to 20,60
Joe is going to 20,65
->joe.Jump();
Joe is jumping
->jim.Jump();
Jim is jumping
->joe.Attack(jim);
Joe is attacking Jim
->

That is cool, isn’t it? So now you know how to expose your ‘mainstream’ objects to Evaluator, for providing some C# scripting features in your application. Happy Coding!!

 

Also, don’t miss my earlier post 4 .NET Libraries You *Should* know better

Read more >>

imageIn my last post, I explained how to host Mono’s C# Compiler As A Service in your .NET applications. In this post, we’ll explore this a bit further, and see how to leverage Mono’s compiler as a service for implementing some dynamic querying features in your .NET applications.

Read my first post How To Host Mono’s C# Compiler as a Service in your .NET Application if you missed it. Now, let us explore some more points about using Mono’s C# Compiler as a Service in general, and the ‘Evaluator’ class in particular, to see how to leverage this for some practical uses like dynamic data filtering.

The Mono.CSharp.Evaluator Class

Let us consider a simple and dirty example. Fire up a Console application in Visual Studio, Add a reference to Mono.CSharp.dll, and try this code. Have a look at the Init method, and Run method of the Mono.CSharp.Evaluator class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.CSharp;

namespace MonoHost
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the evaluator
            Evaluator.Init(new string[0]);

            //Using evaluator to run some code, line by line

            //Importing namespaces 
            Evaluator.Run("using System;");
            Evaluator.Run("using System.Linq;");
            Evaluator.Run("using System.Collections.Generic;");

            //Sum of 'n' numbers
            Evaluator.Run("List<int> numbers= new List<int> {1,2,4,3} ;");
            Evaluator.Run("var sum=0; foreach(var num in numbers) sum+=num;");
            Evaluator.Run("Console.WriteLine(sum);");

        }
    }
}

Sweetening the Run

Of course, we can make the above code sweeter with an extension method. Have a look at this, the above code re-written. Nothing much, just some syntax sweetness.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.CSharp;

namespace MonoHost
{
    // A simple extension method to invoke Evaluator.Run on a string
    public static class EvaluatorExtensions
    {
        public static void Run(this string code, bool repQuotes = false)
        {
            var run = repQuotes ? 
                      code.Replace("'", "\"") : code;
            Evaluator.Run(run);
        }
    }

    //Our main prog
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the evaluator
            Evaluator.Init(new string[0]);

            //Importing namespaces. Note that @”..” is one single string in multiple lines
            @"using System;
              using System.Linq;
              using System.Collections.Generic;"
                .Run();

            //Sum of 'n' numbers
            @"List<int> numbers= new List<int> {1,2,4,3} ;
             var sum=0; 
             foreach(var num in numbers) 
                     sum+=num;
             Console.WriteLine('Result={0}',sum);"
                .Run(true);
        }
    }
}

The Evaluate method

The Evaluator class also has an Evaluate method, that can evaluate an expression and can pass something back to your .NET code. This is pretty interesting, as this allows you to build dynamic queries, predicates etc via plain text, and apply it to your native collections etc. What about creating another LinqPad, your own style? Check out this example, where we query a list of integers by building a dynamic predicate.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.CSharp;

namespace MonoHost
{
    // A simple extension method to invoke Evaluator methods on a string
    public static class EvaluatorExtensions
    {
        public static T Eval<T>(this string code) where T : class
        {
            return Evaluator.Evaluate(code) as T;
        }
        
        public static void Run(this string code, bool repQuotes = false)
        {
            var run = repQuotes ? 
                        code.Replace("'", "\"") : code;
            Evaluator.Run(run);
        }
    }

    //Main Program
    class Program
    {
        static void Main(string[] args)
        {
            //Initializing the evaluator
            Evaluator.Init(new string[0]);

            //Using evaluator to run some code
            //via our Extension method
            @"using System;
              using System.Linq;
              using System.Collections.Generic;"
                .Run();

            List<int> numbers = new List<int> { 1, 30, 90, 23, 46, 22, 50 };

            //Filter the numbers. Dynamic Predicate
            var match=@"new Predicate<int>(num=> num>20 && num <44);".Eval<Predicate<int>>();
            var filtered = numbers.FindAll(match);
            filtered.ForEach(n => Console.WriteLine(n));
        }
    }
}

The interesting point to note in the above example is, we are building our Predicate based on a string. And our Eval extension method is good enough to cast the result to the specified type. Now, there are a handful use cases for this. For example, with a bit of creativity and some pre-processing, you can provide a user friendly query language against data in your view model, to filter records when you build your next data visualizer application. And as an exercise, try modifying the above example with a custom type list, instead of an integer list. You can add a reference to an assembly via the ReferenceAssembly method of the Evaluator class.

Conclusion

Now, it is pretty cool if the context and data can be shared across the main application and the Evaluator context, so that our main app objects and data can be ‘touched’ from the plain text code that’ll be executed by the Evaluator, right? So that we can implement some sort of Scripting functionality via C#!! There are various ways to do that, but that is the topic for my next post. So stay tuned!!

Updated: I blogged the Next Part  - Using C# As A Scripting Language in your .NET Applications

Read some of my previous C# posts – Revisiting Few C# Concepts or 7 Free Ebooks for .NET programmers and Architects etc.

Read more >>

I Love C#Anders in his C# Futures Talk mentioned about C# Compiler as a Service and demonstrated an REPL (Read Evaluation Print Loop) implementation.

If this is going to be a part of C#/.NET framework, this will allow you to execute plain C# code strings during runtime. This will allow you to implement features like interactive scripting in your applications.

As of now, .NET/C# stack don’t have this. Enter Mono’s C# Compiler as a service implementation. Big Bang. Last April, Miguel announced the availability of Mono’s C# Compiler as a Service assembly, along with a neat REPL C# shell. From that point onwards, I was thinking about writing a quick post on some of my thoughts about hosting Mono’s assembly in your .NET applications, so here we go.

1 – Download the C# Shell and Mono.CSharp.dll assembly

A snapshot of the C# REPL shell and Mono.CSharp.dll is available from this direct link (From Miguel’s post). The Zip contains a C# REPL shell - csharp.exe – and also the Mono.CSharp.dll which is the Compiler as Service assembly that we may use to host the C# compiler in our .NET apps.

2 – Exploring Miguel’s C# REPL Shell

For now, fire up csharp.exe. Once you fire up the shell, type help; to get a list of Static methods available for meta purposes like showing the defined local variables (ShowVars), loading an assembly so that you can use the types inside the same (LoadAssembly) etc.

image 

Also, In the above screenshot of the console, you may see that I’m just assigning some value to variable ‘x’, and then printing it to the console.  Also, see this post from Miguel to learn what you can do more with the C# interactive shell - I know you’ve already fallen in love. Mono’s C# console supports {..} block syntax and some of kind of auto completion as well.

3 – Hosting Mono’s Compiler as a Service in your own .NET applications

Now, let us see how to host the Mono.CSharp.dll in your own .NET applications. Create a console application in Visual Studio, and Add a reference to Mono.CSharp.dll. Now, let us try some simple code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Mono.CSharp;

namespace MonoCompilerHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(">Mini Console\n\n");
            while (true) 
            {
                Console.Write(">"); 
                string input = Console.ReadLine();
                if (input == "@@") return;
                Evaluator.Run(input);
            }
        }
    }
}

In the code, you may see that we are importing the Mono.CSharp namespace, so that we can use the Evaluator class in the same. The Evaluator class has a 'Run' static method, that'll take some C# code as string, and execute the same. So, we just wrote a simple REPL leveraing Mono.CSharp.dll, which reads line by line C# code from the console and execute the same. Let us see our Mini Console app in action.

image

Note that our implementation is not very functional, it is just a ‘hello world’ application to demonstrate how to leverage Mono’s compiler as a service in your own .NET apps.

4 – Advanced Scenarios

There are quite a handful of useful scenarios where you can leverage runtime code evaluation/execution. Like, providing scripting features, allowing your users to write queries using LINQ or so, storing some logic in your application as non compiled, decoupled and plain C# code, that’ll be picked, compiled and executed by your system at run time etc etc. Will blog about that later.

Update: Read Second part of this article Dynamic Filtering and Querying in Your .NET applications - Using Mono’s C# Compiler As Service

You may also read some of my recent posts on 7 Free E-Books For .NET Programmers and Architects and Revisiting Few C# Concepts – Delegates, Anon methods, Expression Trees, Lambdas

Read more >>

imageA lot of people ask me for good book recommendations. Hence, for some time, I was thinking about compiling a quick list of useful free E-Books for .NET programmers and budding architects. Most of us start our programming career as a ‘casual’ programmer – My own definition about a ‘Casual’ coder is a guy who can code, but who is least concerned/interested about the beauty, efficiency, extensibility and readability of the code he writes. Some of these books will definitely help us to evolve our coding skills and thought processes for developing better solutions. Hope you find this list useful, here we go.

Foundations Of Programming

The Foundation Of Programming Series Free e-book By Karl Seguin is one of my favorites. It is simple, short and sweet. Especially for ‘casual’ programmers, this will give a better thought process – that’ll definitely enable them to code better and think better. This book covers the ALT.NET Philosophy, Domain Driven Development concepts, DI, TDD etc in a nice way. This book is close to my heart.

Microsoft Application Architecture Guide, 2nd Edition

Published by Microsoft, this is an essential read for any Microsoft.NET developer or Architect to understand the underlying architecture and design principles and patterns for developing successful solutions on the Microsoft platform and the .NET Framework. This guide neatly covers popular architecture patterns, best practices and common challenges you need to understand for developing .NET applications. Get a good grip on developing enterprise applications in .NET.

Rob Miles C# Yellow Book 2010

A nice action packed book that takes you through C# and .NET concepts. This book explains C# language and .NET library in general – with a clear focus on implementation thought process and best practices.

Threading in C#

A short, neatly written book from Joe Albahari about Threading in C#. This is a must read for any .NET programmer to understand more about threading in general, thread pooling, synchronization, Non blocking synchronization, etc. In this book, Joe even covers the Parallel Framework Extensions and Parallel programming in .NET

Improving .NET Application Performance and Scalability

This guide is again from Microsoft, and focuses on designing your applications with Performance and scalability in mind. It has sections relevant to architects, developers, testers, and administrators. Following the checklists and guidance in this book will ensure that there won’t be any unpleasant surprises in the end. Read this guide if you develop Enterprise applications in .NET

Applying Design Patterns

This is a quick introduction towards the thought process of applying design patterns. The objective of the book is to introduce design patterns in a simple way, so that developers can understand some common patterns and how to apply them. I wrote that some time back ;)

RefCardz from DZone

DZone has a number of awesome Ref Cardz (Quick reference sheets) on multiple technologies. You can go to DZone –> RefCardz to browse and download them (after getting a free DZone Id). Here are some of my recent favorites

 

Also, make sure you read 4 .NET 4.0 libraries you should know better and 6 Visual Studio 2010 Tips to boost your productivity

Read more >>

image Let us explore few concepts about Delegates, Anonymous methods, Lambdas and Expression Trees. This is an introductory post, and I’ll follow up with more posts. These code examples are pretty simple, you can fire up a C# Console application in Visual Studio and try these examples if you are interested.

Delegates

We know that a delegate is a type that can reference a method. For example, consider this example to define a delegate and create a delegate instance.

   //Example 1 - Creating a delegate instance using Named method

   public delegate int BinaryOperationDelegate(int x,int y);
   
    class Program
    {
        static void Main(string[] args)
        {
            //Create a delegate instance using named method
            var add = new BinaryOperationDelegate(AddOperation);
            int result = add(20, 30);
            Console.WriteLine(result);
        }

        static int AddOperation(int x,int y)
        {
            return x+y;
        }
    }

The above code will give you an output of 50, no doubt, right ? :)

Anonymous Methods

Now, you may know that with C# 2.0, we can use anonymous methods to create a delegate instance with out a named method. Let us re-write the above implementation leveraging an anon method. Instead of the method name, you’ve to use the ‘delegate’ keyword. Also, note that there is no need to specify a return type – because the return type will be inferred from the delegate signature.

   

   //Example 2 - Creating a delegate instance using Anon method

   public delegate int BinaryOperationDelegate(int x,int y);

    class Program
    {
        static void Main(string[] args)
        {
            //Create a delegate instance using anon method
            BinaryOperationDelegate add= 
                    delegate(int a, int b) { return a+b;} ; 
            int result = add(20, 30);
            Console.WriteLine(result);
        }

    }

Lambdas

And of course, you might also know that with C# 3.0, you can use Lambdas for producing anonymous methods. A lamda expression is exactly a function, that can contain statements and expressions. Here is the equivalent of above code, still shortened using a lambda

    
   //Example 3 - Creating a delegate instance using statement lambda

    public delegate int BinaryOperationDelegate(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            //Create a delegate instance using a statement lambda
            BinaryOperationDelegate add =(a,b)=>{
                                                //this statement block can contain 
                                                //multiple statements  
                                                return a+b; 
                                                };

            int result = add(20, 30);
            Console.WriteLine(result);
        }


    }    

In the above example, note the lambda syntax that replaces the anon method syntax in example 2
(a,b)=>{
            return a+b; 
       };

The types of input parameters a and b and the return type will be inferred correctly by the compiler, based on the context. How ever, on scenarios where the compiler can't infer the type directly, you can provide that explicitly. Like this.

    BinaryOperationDelegate add =(int a, int b)=>{ return a+b; };

There are basically two type of lambdas - Statement Lamdas and Expression Lambdas. The above example shows a statement lambda, as the right hand expression is inside a statement block, of the form
(param1, param2)=> { statement1; statement2; } ;

If you won't have input parameters, you may use the syntax
()=> { statement1; statement2; } ;

=> simply means 'goes to', and you may say that the input parameters goes to the statements (for some processing) :)

Statement Lambdas And Expression Lambdas


We’ve seen how to create Statement lambdas in the above example. Now, let us explore a bit about Expression Lambdas (or single line lambdas). The syntax is similar to statement lambdas, but for expression lambdas, the right hand expression should not be inside a statement block  { }. Instead of having statements on the right side, an Expression Lambda can have a single line expression on the right hand side. Here is the simple example, with out the statement block.
    public delegate int BinaryOperationDelegate(int x, int y);

    class Program
    {
        static void Main(string[] args)
        {
            //Expression Lambda
            BinaryOperationDelegate add =(a, b)=>a+b;
            int result = add(20, 30);

            Console.WriteLine(result);
        }
    }
The above code produces the same result as in the case of stament lambdas. How ever, Expression lamdba has an advantage over statement lambda. When an expression lambda is assigned to a variable of type Expression, the compiler emits code to build an expression tree that represents the lambda expression, instead of a delegate instance.
   //Example 4 - Expression Lambdas

    public delegate int BinaryOperationDelegate(int x, int y);

    class Program
    {
        static void Main(string[] args)
        {
            //Expression Lambda to delegate instance
            BinaryOperationDelegate add =(a, b)=>a+b;
            int result1 = add(20, 30);

            //Expression Lambda to Expression tree
            Expression<BinaryOperationDelegate> addExpr = (a, b) => a + b;

            //Let us compile the expression tree before executing the same
            var compiledAdd = addExpr.Compile();
            int result2=compiledAdd(20,30);
            

            Console.WriteLine(result1);
            Console.WriteLine(result2);
        }
    }


In the above example, you saw that we are assigning our expression lambda to the System.Linq.Expression<TDelegate> to create an expression tree, and the compiling it to get the actual delegate. Expression trees provide us a powerful way to represent code/logic as data, that can be modified and/or interpreted at runtime if required.

Example Usages for Lambdas

These are some of the areas you may find using Lambdas pretty often.

To provide inline event handlers like

 button.Click += (sender,args) =>
{
};

To find items in a collection

  var dogs= animals.Where(animal => animal.Type == "dog");

For iterating a collection, like

 animals.ForEach(animal=>Console.WriteLine(animal.Name));

Creating a custom object

 var myObj= mySource.Select(x => new {Name = x.name, Age= x.age});

Simple one line methods

 Func<int, int> add = x => x + x;

For aggregate operations

 double charCount = document.Sum(word => word.Length)

What is next?

As mentioned, this was an intro post for a couple of interesting posts I've in mind. I'll follow up this post with few more posts on Generic Delegates, Delegate Chaining, Type inference in generic delegates and methods and why they are interesting, Creating and parsing expression trees using Expression tree APIs etc. Stay tuned

Read more >>

top