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;

     }
 }
}

Autocomplete using Jquery

aspdotnetcodebook
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>

    <title></title>
    <style type="text/css">
        .listbox
        {
            position: relative;
            left: 10px;
            margin: 10px;
            width: 200px;
            background-color: #000;
            color: #fff;
            border: 2px solid #000;
        }
        .nameslist
        {
            margin: 0px;
            padding: 0px;
            list-style: none;
        }
        .hover
        {
            background-color: Teal;
            color: blue;
        }
    </style>

    <script type="text/javascript">
        $(document).ready(function() {
            $('.listbox').hide();
            $('#country').keyup(function() {
                var country = $('#country').val();
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/User",
                    data: "{'country': '" + country + "'}",
                    dataType: "json",
                    contentType: "application/json",
                    success: function(html) {
                        $('.listbox').show();
                        $('.nameslist').html(html.d);
                        $('li').hover(function() {
                            $(this).addClass('hover');
                        }, function() {
                            $(this).removeClass('hover');
                        });
                        $('li').click(function() {
                            $('#country').val($(this).text());
                            $('.listbox').hide();
                        });
                    }
                });
                return false;
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <span class="label">Enter Country Name</span>
    <input type="text" name="country" id="country" />
    <div class="listbox">
        <div class="nameslist">
        </div>
    </div>
    </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [System.Web.Services.WebMethod]
    public static string User(string country)
    {

        Country objCountry = new Country();
        var query = from p in objCountry.GetList()
                    where p.CountryName.ToLower().StartsWith(country.ToLower())
                    select p;
        StringBuilder sb = new StringBuilder();
        foreach (var item in query)
        {
            sb.Append("<li>" + item.CountryName + "</li>");

        }
        return sb.ToString();
    }

}

public class Country
{
    public int ID { get; set; }
    public string CountryName { get; set; }


    public List<Country> GetList()
    {
        List<Country> list = new List<Country>()
        {
            new Country(){ID=1,CountryName="Inida"},
            new Country(){ID=2,CountryName="USA"},
            new Country(){ID=3,CountryName="UK"},
            new Country(){ID=4,CountryName="Australia"},
            new Country(){ID=5,CountryName="Newzeland"}

        };
        return list;
    }
}

LINQ2SQL

aspdotnetcodebook In this post i will show mapping of Linq query with SQL query
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title></title>
   <style type="text/css">
       .style1
       {
           width: 100%;
       }
   </style>
</head>
<body>
   <form id="form1" runat="server">
   <div>
   </div>
   <table class="style1">
       <tr>
           <td>
               <asp:Button ID="btnSelect" runat="server" Text="Select Statement" OnClick="btnSelect_Click" />
           </td>
           <td rowspan="9">
               <asp:TextBox ID="txtOutput" runat="server" TextMode="MultiLine" Height="350px" Width="390px"></asp:TextBox>
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnInnerJoin" runat="server" Text="Inner Join" OnClick="btnInnerJoin_Click"
                   Width="152px" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnLeftJoin" runat="server" Text="Left Join" OnClick="btnLeftJoin_Click"
                   Width="151px" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnMax" runat="server" Text="Max" OnClick="btnMax_Click" Width="151px" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnOrderBy" runat="server" Text="OrderBY" Width="151px" OnClick="btnOrderBy_Click" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnDistinct" runat="server" Text="Distinct" OnClick="btnDistinct_Click"
                   Width="150px" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnLike" runat="server" Text="Like" Width="149px" OnClick="btnLike_Click" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnSwitchCase" runat="server" Text="SwitchCase" Width="147px" OnClick="btnSwitchCase_Click" />
           </td>
       </tr>
       <tr>
           <td>
               <asp:Button ID="btnIn" runat="server" Text="In Operator" Width="146px" OnClick="btnIn_Click" />
           </td>
       </tr>
   </table>
   </form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
   StudentDataContext dc = new StudentDataContext();
   protected void Page_Load(object sender, EventArgs e)
   {



   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnSelect_Click(object sender, EventArgs e)
   {

       var querySelect = from s in dc.Students
                         select s;
       txtOutput.Text = querySelect.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnInnerJoin_Click(object sender, EventArgs e)
   {
       var queryInnerJoin = from c in dc.Students
                            join m in dc.Marks
                            on c.StudentID equals m.StudentId
                            select new
                            {
                                StudentId = c.StudentID,
                                StudentName = c.Name,
                                Mark = m.Marks

                            };
       txtOutput.Text = queryInnerJoin.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnDistinct_Click(object sender, EventArgs e)
   {
       var queryDistinct = (from s in dc.Students
                            select s).Distinct();
       txtOutput.Text = queryDistinct.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnLeftJoin_Click(object sender, EventArgs e)
   {
       var queryJoin = from c in dc.Students
                       join m in dc.Marks
                       on c.StudentID equals m.StudentId
                       into StudentMarks
                       from joinedstudent in StudentMarks.DefaultIfEmpty()
                       select new
                       {
                           StudentId = c.StudentID,
                           StudentName = c.Name,
                           Age = c.Age,
                           Marks = joinedstudent.Marks


                       };
       txtOutput.Text = queryJoin.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnMax_Click(object sender, EventArgs e)
   {
       var queryMax = from c in dc.Students

                      where c.Marks.Max(x => x.Marks > 50 || x.Marks < 90)
                      select c;


       txtOutput.Text = queryMax.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnLike_Click(object sender, EventArgs e)
   {
       var queryLike = dc.Students.Where(x => x.Name.Contains("S"));

       txtOutput.Text = queryLike.ToString();

   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnSwitchCase_Click(object sender, EventArgs e)
   {
       var swishCase = from c in dc.Students
                       select new
                       {
                           //ternary operator of switch case
                           StudentName =
                            (
                            c.StudentID == 1 ? "Student1" :
                             c.StudentID == 2 ? "Student2" :
                             c.StudentID == 3 ? "Student3" :
                              "Opps"
                             )

                       };
       txtOutput.Text = swishCase.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnIn_Click(object sender, EventArgs e)
   {
       string[] names = { "Student1", "Student2" };
       var filterdQuery = from c in dc.Students
                          where names.Contains(c.Name)
                          select c;
       txtOutput.Text = filterdQuery.ToString();
   }
   /// <summary>
   /// 
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   protected void btnOrderBy_Click(object sender, EventArgs e)
   {
       var queryGroup = from c in dc.Students
                        join m in dc.Marks
                        on c.StudentID equals m.StudentId
                        orderby c.Age descending
                        select new
                        {
                            StudentName = c.Name,
                            Age = c.Age,
                            Marks = m.Marks


                        };
       txtOutput.Text = queryGroup.ToString();
   }
}

Difference between "throw" and "throw ex" in .NET

Diffrence between throw and throw ex In this post i will show what is diffrence between throw and throw ex.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ExceptionGotcha
{

    public class Foo
    {
        /// <summary>
        /// Method that throw the exception.
        /// </summary>
        public static void MethodWithAttitude()
        {
            throw new ApplicationException();
        }
    }
    class Program
    {
        /// <summary>
        /// 
        /// </summary>
        static void Method()
        {
            try
            {
                Foo.MethodWithAttitude();
            }
            catch (Exception ex)
            {


                throw ex;
            }

        }
        static void Main(string[] args)
        {
            Method();

        }
    }
}
From the above code it is clear that exception is in the Foo class but if you execute this code then it will show exception in Program(Method) class.Where is the problem?.Let's modified the code little bit instead of throw ex put throw and instead of Exception ex put Exception and then execute the code it will show exception in Foo class. From above code it is clear that there is a diffrence between throw and throw ex
  1. throw ex resets the stack trace (so your errors would appear to originate from some other place)
  2. throw doesn't - the original stack trace would preserved.
  3. At MSIL level throw converted to rethrow

How To Create Assembly with more than One Module

In this post i will show how to create assembly which contains more than one module. Create below files in the same folder Bar.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Module
{
public class Bar
{
    public override string ToString()
    {
        return "Hi from Bar";
    }
}
}


Foo.cs

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

namespace Module
{
class Foo
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello from Foo");
        Bar obj = new Bar();
        Console.WriteLine(obj.ToString());
        Console.ReadLine();
    }
}
}

Now go to visual studio command prompt and change to the source file and execute the following command