Thursday, March 7, 2013

Clay, the power of JavaScript within C#

The code:

using System;
using System.Linq;
using System.Collections.Generic;
 
using System.Dynamic;
 
using ClaySharp;
 
 
 
namespace TheDynamic
{
    class Program
    {
        static void Main(string[] args)
        {
            // SampleExpando();
            SampleClay();
        }
 
        static void SampleExpando()
        {
            dynamic d = new ExpandoObject();
           
            d["LoremIpsum"] = "World"; // ExpandoObject limitation, dictionary-property duality is not possible
            Console.WriteLine("Hello {0}", d.LoremIpsum);
           Console.ReadLine();
        }
 
 
        // Clay: The power of JavaScript within C#
        // http://www.hanselman.com/blog/NuGetPackageOfTheWeek6DynamicMalleableEnjoyableExpandoObjectsWithClay.aspx
        static void SampleClay()
        {
           
            dynamic New = new ClayFactory();
           
            
            var great = New.Blah();
         
            // just to prove Clay is more dynamic than ExpandoObject, you can add things at runtime, and access them as property:
            // string s = Console.ReadLine(); // Enter this: LoremIpsum
            // great[s]
 
 
            // You can set things via dictionary approach
            great["LoremIpsum"] = "World";         
            // And access them through both property or dictionary approach, just like in JavaScript
            Console.WriteLine("Hello: {0} {1}", great.LoremIpsum, great["LoremIpsum"]);
 
 
            // And vice versa, you can set things using property approach
            great.Awe = "Some";
            // And access them through both dictionary or property approach, just like in JavaScript
            Console.WriteLine("Feelings: {0} {1}", great["Awe"], great.Awe);
 
           
            var props = new Dictionary<string, object>();
 
 
            Func<object> nullFunc = () => null;
 
            var clayBehaviorProvider = great as IClayBehaviorProvider;
            clayBehaviorProvider.Behavior.GetMembers(nullFunc, great, props);
 
 
            Console.WriteLine("\n\nLaugh the problems: \n");
 
            foreach (KeyValuePair<string, object> kv in props.Skip(1))
            {
                Console.WriteLine("{0} {1}", kv.Key, kv.Value);
            }
 
            Console.ReadLine();
        }
    }
 
    // Good read, Clay in action, in ASP.NET MVC! http://orchard.codeplex.com/discussions/406947
}
 

The output:

Hello: World World
Feelings: Some Some
 
 
Laugh the problems:
 
LoremIpsum World
Awe Some 

No comments:

Post a Comment