Quote of the day

Any fool can write code that a computer can understand. Good programmers write code that humans can understand

How To create your own DynamicObject

In this post i will show how to create your own dyanamic object in c# 4.0.Create a class and Inherit it from DyanicObject (Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly).It has following virtual method that you must override to add dynamic behavior to your class.
        // Summary:
        //     Returns the enumeration of all dynamic member names.
        //
        // Returns:
        //     The list of dynamic member names.
        public virtual IEnumerable<string> GetDynamicMemberNames();
        //
        // Summary:
        //     The provided MetaObject will dispatch to the Dynamic virtual methods. The
        //     object can be encapsulated inside of another MetaObject to provide custom
        //     behavior for individual actions.
        //
        // Parameters:
        //   parameter:
        //     The expression representing the MetaObject to dispatch to the Dynamic virtual
        //     methods.
        //
        // Returns:
        //     The object of the System.Dynamic.DynamicMetaObject type.
        public virtual DynamicMetaObject GetMetaObject(Expression parameter);
        //
        // Summary:
        //     Provides the implementation of performing a binary operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   arg:
        //     The right operand for the operation.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result);
        //
        // Summary:
        //     Provides the implementation of converting the DynamicObject to another type.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the conversion.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryConvert(ConvertBinder binder, out object result);
        //
        // Summary:
        //     Provides the implementation of creating an instance of the DynamicObject.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments used for creation.
        //
        //   result:
        //     The created instance.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of performing a delete index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes to be deleted.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes);
        //
        // Summary:
        //     Provides the implementation of deleting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryDeleteMember(DeleteMemberBinder binder);
        //
        // Summary:
        //     Provides the implementation of performing a get index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes that will be used in the operation.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result);
        //
        // Summary:
        //     Provides the implementation of getting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the get operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryGetMember(GetMemberBinder binder, out object result);
        //
        // Summary:
        //     Provides the implementation of invoking the DynamicObject.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments that will be used for the invocation.
        //
        //   result:
        //     The result of the invocation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of calling a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   args:
        //     The arguments that will be used for the invocation.
        //
        //   result:
        //     The result of the invocation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result);
        //
        // Summary:
        //     Provides the implementation of performing a set index operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   indexes:
        //     The indexes that will be used in the operation.
        //
        //   value:
        //     The value to set.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value);
        //
        // Summary:
        //     Provides the implementation of setting a member.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   value:
        //     The value to set.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TrySetMember(SetMemberBinder binder, object value);
        //
        // Summary:
        //     Provides the implementation of performing a unary operation.
        //
        // Parameters:
        //   binder:
        //     The binder provided by the call site.
        //
        //   result:
        //     The result of the operation.
        //
        // Returns:
        //     Returns true if the operation is complete, false if the call site should
        //     determine behavior.
        public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace CustomDyamicObject
{
  class Program
  {
      static void Main(string[] args)
      { //Custom Dynamic Object
          dynamic bag = new Bag();
          bag.Name = "Hello C#";
          bag.Age = 12;
          Console.WriteLine("{0}-{1}", bag.Name, bag.Age);
          Action<dynamic> hi = (self) => Console.WriteLine("Hello from {0}", self.Name);
          bag.SayHi = hi;
          bag.SayHi();
          Console.ReadLine();
      }
  }
  public class Bag : DynamicObject
  {
      Dictionary<string, object> _data = new Dictionary<string, object>();
      public override bool TryGetMember(GetMemberBinder binder, out object result)
      {
          result = _data[binder.Name];
          return true;

      }
      public override bool TrySetMember(SetMemberBinder binder, object value)
      {
          _data[binder.Name] = value;
          return true;

      }

      public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
      {
          dynamic target = _data[binder.Name];
          int length = args.Length;
          if (length == 0)
          {
              target(this);
              result = true;
              return true;
          }
          else if (length == 1)
          {
              target(this, args[1]);

              result = true;
              return true;

          }
          else
          {
              throw new NotImplementedException();
          }


      }
  }
}

ExpandoObject and Dynamic Programming in c# 4.0

ExpandoObject is a new Object in the .NET Framework that allows you to add and remove properties, methods, and events at runtime just like JavaScript Object. The following example demonstrates how to add two new values and a method in c# and Javascript.
C# Code JavaScript Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Dynamic;

namespace CSharpDemo
{
    class Program
    {

        static void Main(string[] args)
        {
            dynamic customer = new ExpandoObject();
            customer.City = "Gurgaon";
            customer.Country = "India";
            customer.FullAddress = new Action(() => Console.WriteLine(
                customer.City + " " + customer.Country
                ));
            customer.FullAddress();
            Console.ReadKey();
        }

    }
}
 
        function GetCusomer() {
            var customer = new Object();
            customer.City = "Gurgaon";
            customer.Country = "India";
            customer.FullAddress = function () {
                return this.City + "," + this.Country;
            }
            alert(customer.FullAddress());
        }

Named and Optional Parameters

Named parameters allow you to pass parameters into a function in any order. To use a named parameter, simply specify the parameter name followed by a colon and then the value you are passing into a function. The following code illustrates passing the named parameter.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSharpDemo
{
    class Program
    {

        static void Main(string[] args)
        {
           
            //Calling mehtod without named parameter
            AddNumbers(1, 2, 3);
            //Calling method with named parameter
            AddNumbers(c: 3, b: 2, a: 4,d:10);
            Console.ReadLine();

        }
        public static void AddNumbers(int a, int b, int c, int d = 0)
        {
            int sum = a + b + c + d;
            Console.WriteLine("Sum={0}", sum);

        }
    }
}

There some rules you need to be aware of when working with named parameters.

  • Non-optional parameters must be declared first.
  • Non-optional parameters must still be specified when you call a method.
  • Parameters are evaluated in the order they are declared.
  • If two function signatures are equally valid for your input, then the one with no optional values is given precedence.

How to create xml from Collection using Linq

In this post i am going to show you how to create xml from database(for demo purpose i have created a List of person).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Linq2XML
{
 public class Program
 {
     static void Main(string[] args)
     {
         var xml = new XDocument(new XComment("Your Comment"), new XElement("Persons",
                   from c in new Person().GetList()
                   where c.FirstName.StartsWith("B")
                   select new XElement("Person",
                             new XAttribute("FirstName", c.FirstName),
                             new XAttribute("LastName", c.LastName))));

         Console.WriteLine(xml);
         Console.ReadLine();



     }
 }
 public class Person
 {
     public int ID { get; set; }
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public List<Person> GetList()
     {
         List<Person> list = new List<Person>()

         {
             new Person(){ID=1,FirstName="John",LastName="John"},
             new Person(){ID=2,FirstName="Bill",LastName="Gates"},
             new Person(){ID=3,FirstName="Barak",LastName="Obama"}


         };


         return list;

     }
 }
}