Translate

Monday 26 October 2015

Advantage to using ASP.Net MVC vs web forms

The main advantages of ASP.net MVC are:
  1. Enables the full control over the rendered HTML.
  2. Provides clean separation of concerns(SoC).
  3. Easy integration with JavaScript frameworks.
  4. Following the design of stateless nature of the web.
  5. RESTful urls that enables SEO.
  6. No ViewState and PostBack events
The main advantage of ASP.net Web Form are:
  1. It provides RAD development
  2. Easy development model for developers those coming from winform development.

Monday 12 October 2015

Set a delay in a jQuery / Ajax function

// set your delay here, 2 seconds as an example...
var my_delay = 2000;

// call your ajax function when the document is ready...
$(function() {
    callAjax();
});

// function that processes your ajax calls...
function callAjax() {
    $.ajax({
        // ajax parameters here...
        // ...
        success: function() {
            setTimeout(callAjax, my_delay);
        }
    });
}

Tuesday 8 September 2015

How do I convert a dictionary/List to a JSON String in C#?

using System.Web.Script.Serialization;

 Dictionary<string, string> name = new Dictionary<string, string>();
        name.Add("1", "GKSamy");
        name.Add("2", "Rakshitta");
        string myJsonString = (new JavaScriptSerializer()).Serialize(name);

How can I block F12 keyboard key, CTRL+SHIFT+i and Prevent from Right Click

<script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
    <script language="JavaScript">

        //////////F12 disable code////////////////////////
        document.onkeypress = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                //alert('No F-12');
                return false;
            }
            else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) {
                return false;  //Prevent from ctrl+shift+i
            }

        }
        document.onmousedown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                //alert('No F-keys');
                return false;
            }
            else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) {
                return false;  //Prevent from ctrl+shift+i
            }
        }
        document.onkeydown = function (event) {
            event = (event || window.event);
            if (event.keyCode == 123) {
                //alert('No F-keys');
                return false;
            }
            else if (event.ctrlKey && event.shiftKey && event.keyCode == 73) {
                return false;  //Prevent from ctrl+shift+i
            }
        }

     ////////////////////Prevent from Right Click Inspect Element /////////////////////////////
        $(document).on("contextmenu", function (e) {
            e.preventDefault();
            alert('Right Click is not allowed');
        });
        /////////////////////end///////////////////////
    </script>

Monday 3 August 2015

Where are my asp.net website compiled assembly files stored on my computer?

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

It's possible to force the temp path to a specific location by a property to the compilation tag in the web.config.

<compilation tempDirectory=“E:\ASP.Net Temporary Folder\” debug=“false“>

Thursday 23 July 2015

WCF Features

WCF is a Microsoft framework for building Service-Oriented applications.

Features of WCF

  • WCF hosting - If we are working with web services then only option we are having is hosting it inside web server such as IIS using http or wshttp protocols. But WCF supports four types of hosting
    • IIS
    • WAS (Windows process activation services)
    • Self-hosting
    • Windows services
    Message transmission - Messages can be transmitted between clients and service via various transport protocols and encodings such as SOAP using http and binary data using TCP.
  • Serialization - Web services uses XmlSerializer for transferring data between service calls whereas WCF supports multiple serializers
    • DataContractSerializer(faster and supports versioning)
    • NetDataContractSerializer(when it required to include CLR type information in the serialized XML)
    • XmlSerializes(mostly to support backward compatibility).
  • Multiple technologies at one place - WCF unites following four technologies
    • .NET remoting
    • MSMQ
    • Web Services
    • COM+
  • Message Contract - In Web services customizing the headers of the SOAP message was a tedious task. For that we were supposed to derive a class from SoapHeader and then SoapHeaderAttribute is used to indicate the presence of the header.
    But with WCF we can make it easily with the help of simple attributes like MessageContractAttribute, MessageHeaderAttribute, and MessageBodyMemberAttribute.
  • Multiple Message Patterns - WCF supports three message patterns that describe how client and service pass messages
    • Request-Reply Pattern – Client sends message to service and waits for reply.
    • One-Way Message Pattern – Client sends message to service but service does not reply message to client.
    • Duplex pattern – Both client and the service can initiate communication. The client calls a method of the service. The service can then use a client callback to call a method in the client.
  • Security - In WCF security can be implemented with the help of well-known standards such as SSL.
  • Reliable - WCF supports reliable messages with the help of Queues and reliable sessions.
  • REST - WCF can be extended to support plain xml data that is not wrapped in a soap envelope, xml formats such as ATOM and non xml standard such as JSON.
  • WCF Transaction - - WCF supports to create distributed transactions for your service application. Transaction is a collection of logical operations which need to be run as a single logical unit.
    (Either all operations will successfully execute and completes or in case any of them fail others will rollback).
  • WCF instancing - In WCF we can control the way WCF service objects are instantiated in the WCF server. WCF Framework comes up with following instancing models
    • Per Call - A new instance will be created for every client request.
    • Per session - A new instance is created for each new client session and maintained for the lifetime of that session.
    • Single - A single instance handles all client requests for the lifetime of the application.
  • WCF Concurrency - With WCF Concurrency features we can control how service instances can serve multiple requests at the same time. We have three choices
    • Single – Only one request will be served at a time.
    • Multiple - Multiple requests can be handled by the WCF service object at any given moment of time.
    • Reentrant - A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call a WCF client through callback and reenter without deadlock.

What is ABC in WCF

We had gone through the feature of WCF and understood why its termed as advanced version of web services. Now it’s time to answer a very basic question related to WCF i.e., what is ABC of WCF?
When we say WCF, we came across end points. Service endpoint can be a part of continuously hosted service hosted in IIS or service hosted in an application.
ABC or Address, Binding and Contract are the three elements which constitutes and Service Endpoint.
  • Address - Where Service is residing (URL of the service.)
  • Binding – How to talk to the service?
  • Example – basicHttpBinding, wsHttpBinding, webHttpBinding etc.
  • Contract – What can the service do for me?

Monday 22 June 2015

GridView Fixed Header and Freeze Column

 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
    <link href="../Css/GridviewScroll.css" rel="stylesheet" />
    <script src="../Scripts/gridviewScroll.min.js"></script>

    <script type="text/javascript">

        var windowSize;

        // Don't try this - $(window).load(function ()
        function pageLoad() {
            windowSize = $(window).width();
            gridviewScroll();
        }

        $(window).resize(function () {
            windowSize = $(window).width();
            gridviewScroll();
        });

        function gridviewScroll() {
            $('#<%=GridView1.ClientID%>').gridviewScroll({
                width: windowSize - 44,
                height: 350
                freezesize: 2
                // Maintain Scroll position
                startVertical: $("#<%=hfGridView1SV.ClientID%>").val(),
                startHorizontal: $("#<%=hfGridView1SH.ClientID%>").val(),
                onScrollVertical: function (delta) {
                            $("#<%=hfGridView1SV.ClientID%>").val(delta);
                     },
                onScrollHorizontal: function (delta) {
                            $("#<%=hfGridView1SH.ClientID%>").val(delta);
                    }

            });
        }
    </script>

 <div style="width: 100%; margin-left: 2%; margin-right: 2%;">
<asp:GridView ID="GridView1" runat="server" Width="100%"
    AutoGenerateColumns="false" GridLines="None">
    <Columns>

    </Columns>
    <HeaderStyle CssClass="GridviewScrollHeader" />
    <RowStyle CssClass="GridviewScrollItem" />
    <PagerStyle CssClass="GridviewScrollPager" />
</asp:GridView>

<asp:HiddenField ID="hfGridView1SV" runat="server" /> 
<asp:HiddenField ID="hfGridView1SH" runat="server" />

</div>

Ref:  http://gridviewscroll.aspcity.idv.tw/Demo.aspx



Tuesday 16 June 2015

Mapping and Importing Excel Files to a Database using SqlBulkCopy

public void importExcelData(ListItemCollection dbColumns, ListItemCollection excelColumns,
        String tableName)
    {
 
        //set up and make connection
        //connection string specified in the web.config
        ConnectionStringSettings connString = 
              ConfigurationManager.ConnectionStrings["Conn"];
        SqlConnection conn = new SqlConnection(connString.ConnectionString);
        conn.Open();
        using (SqlBulkCopy s = new SqlBulkCopy(conn))
        {
            try
            {
                s.DestinationTableName = tableName;
                s.NotifyAfter = 10000;
                for (int i = 0; i &lt; dbColumns.Count; i++)
                {
                    s.ColumnMappings.Add(excelColumns[i].Value.ToString(),
                       dbColumns[i].Value.ToString());
                }
                s.WriteToServer(data);
                s.Close();
            }
            catch(Exception ex)
            {
                //Error handling
            }
        }
        conn.Close();
    }
Ref: http://blog.shuasolutions.com/2008/10/mapping-and-importing-excel-files-to-a-database-using-sqlbulkcopy/

Friday 29 May 2015

Download All type of File in Web

protected void btnDownLoad_Click(object sender, EventArgs e)
        {
            string FilePath = txtFileLogPath.Text.Trim();
            string fileName = Path.GetFileName(FilePath);
            string fileExtension = Path.GetExtension(FilePath);
            if (!string.IsNullOrEmpty(fileExtension))
            {
                System.IO.FileStream fs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
                byte[] bt = new byte[fs.Length];
                fs.Read(bt, 0, (int)fs.Length);
                fs.Close();
                Response.ContentType = "application/x-unknown/octet-stream";
                Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + fileName);
                try
                {
                    if (bt != null)
                    {
                        System.IO.MemoryStream stream1 = new System.IO.MemoryStream(bt, true);
                        stream1.Write(bt, 0, bt.Length);
                        Response.BinaryWrite(bt);
                        Response.Flush();
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(ex.Message);
                    txtFileLogPath.Text = "";
                    Display(this.GetType(), "Error", "Error Occured");
                }
                finally
                {
                    Response.End();
                    txtFileLogPath.Text = "";
                }
            }
            else
            {
                Display(this.GetType(), "Warning", "Please enter correct path with extension");
                txtFileLogPath.Text = "";
            }
        }
        private void Display(Type t, string errorCaption, string errorMessage)
        {
            string scriptError = "<script>alert('" + errorMessage + "');</script>";
            Page.ClientScript.RegisterStartupScript(this.GetType(), errorCaption, scriptError);
        }

Wednesday 27 May 2015

Why/Can we use 'virtual' for properties in classes?

public class Employee
{
   public int EmpID { get; set; }
   public string EmpName{ get; set; }  
   public string Address { get; set; }
   public virtual ICollection<Dept> dept{ get; set; }
}

public class Dept
{
   public int DeptID{ get; set; }
   public string DeptName{ get; set; }
   public string Email { get; set; }
   public virtual Division div { get; set; }
}
--------------------------------------------------------------------------------------

The virtual keyword has an effect when used on properties in EF Code First.

  • Lazy Loading: Any virtual ICollections will be lazy-loaded unless you specifically mark them otherwise.
  • More efficient change tracking. If you meet all the following requirements then your change tracking can use a more efficient method by hooking your virtual properties. From the link:
To get change tracking proxies, the basic rule is that your class must be public, non-abstract or non-sealed. Your class must also implement public virtual getters/setters for all properties that are persisted. Finally, you must declare collection based relationship navigation properties as ICollection<T> only. They cannot be a concrete implementation or another interface that derives from ICollection<T> (a difference from the Deferred Loading proxy)



Tuesday 19 May 2015

Download multiple excel sheet using NPOI.dll

Download latest NPOI.dll and add into your project reference.


using NPOI.HSSF.UserModel;

 public partial class WebForm1 : System.Web.UI.Page
    {
        string Connstring = ConfigurationManager.ConnectionStrings["Test"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            GetData();
        }

        private void GetData()
        {
            DataSet ds = new DataSet();
            string[] tableNames;
            using (SqlConnection con = new SqlConnection(Connstring))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "ExcelDownload";

                    SqlParameter param = new SqlParameter("@tableNames", SqlDbType.VarChar,50);
                    param.Direction = ParameterDirection.Output;
                    param.Value = 50;
                    cmd.Parameters.Add(param);


                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {
                        da.Fill(ds);
                        string strTableNames = Convert.ToString(cmd.Parameters["@tableNames"].Value);
                        tableNames = strTableNames.Split(',');
                    }

                }
            }

            writeDataToExcelFile(ds, tableNames);
        }
        private void writeDataToExcelFile(DataSet ds, string[] tableNames)
        {
            for (int i = 0; i < tableNames.Length; i++)
            {
                ds.Tables[i].TableName = tableNames[i];
            }
            var workbook = new HSSFWorkbook();
            string filename = "MultiplesheetDownloadDemo";
            for (int i = 0; i < ds.Tables.Count; i++)
            {
                DataTable dt = ds.Tables[i];
                if (dt.Rows.Count > 0)
                {
                    var Sheet = workbook.CreateSheet(ds.Tables[i].TableName);

                    int cols = 0;
                    var myRow = Sheet.CreateRow(0);
                    var style1 = workbook.CreateCellStyle();

                    // cell background
                    style1.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Violet.Index;

                    // font color
                    var font1 = workbook.CreateFont();
                    font1.Color = NPOI.HSSF.Util.HSSFColor.Blue.Index;
                    style1.SetFont(font1);


                    foreach (DataColumn column in dt.Columns)
                    {
                        var Cell = myRow.CreateCell(cols);
                        Cell.SetCellValue(column.ColumnName);
                        Cell.CellStyle = style1;
                        cols++;
                    }


                    for (int rowNum = 0; rowNum < dt.Rows.Count; rowNum++)
                    {
                        myRow = Sheet.CreateRow(rowNum + 1);
                        for (int cellNum = 0; cellNum < dt.Columns.Count; cellNum++)
                        {
                            var Cell = myRow.CreateCell(cellNum);
                            Cell.SetCellValue(Convert.ToString(dt.Rows[rowNum][cellNum]));
                        }

                    }
                }
            }
            using (var buffer = new MemoryStream())
            {
                workbook.Write(buffer);

                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", filename + ".xls"));
                Response.Clear();
                Response.BinaryWrite(buffer.GetBuffer());
                Response.End();
            }


        }
    }

Stored Procedure:

ALTER PROC ExcelDownload
(
@tableNames VARCHAR(500) OUTPUT
)
AS
BEGIN
SET @tableNames = 'tblTable1,tblTable2'
SELECT * FROM dbo.tblTable1
SELECT * FROM dbo.tblTable2
END

Friday 15 May 2015

Insert Stored Procedure Results Into Table

CREATE PROCEDURE GetList
AS
BEGIN
SELECT
ListName = 'MyList'
,ListNumber = 1
END
GO

-- this table will house our results
CREATE TABLE #List
(
ListName VARCHAR(25),
ListNumber INT
)

-- finally, execute and insert into our table
INSERT INTO #List
(
ListName,
ListNumber
)
EXEC dbo.GetList

select * from #List

Wednesday 1 April 2015

MVC application life cycle


Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

Creating Response object: - 
The request object creation has four major steps. Below is the detail explanation of the same.

Step 1 Fill route: - 
MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route:- Depending on the URL sent "UrlRoutingModule" searches the route table to create "RouteData" object which has the details of which controller and action to invoke.

Step 3 Request context created: - The "RouteData" object is used to create the "RequestContext" object.

Step 4 Controller instance created: - This request object is sent to "MvcHandler" instance to create the controller class instance. Once the controller class object is created it calls the "Execute" method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.

Step 5 Execute Action: - The "ControllerActionInvoker" determines which action to executed and executes the action.

Step 6 Result sent: - The action method executes and creates the type of result which can be a view result , file result , JSON result etc.


So in all there are six broad steps which get executed in MVC application life cycle.

Saturday 31 January 2015

Delegate, MultiDelegate with an example

1.       What is Delegate:
A delegate is a type safe function pointer. That is it holds a reference (Pointer) to a function.
The signature of the delegate must match on the signature of the function, the delegate points to; otherwise you get a compiler error. This is the reason delegates are called as a type safe function pointers.
A delegate is similar to a class. You can create an instance of it, and when you do so, you pass in the function name as a parameter to the delegate constructor, and it to this function the delegate will point to.
Note: Delegate syntax is similar to method syntax with a delegate keyword.
Example:
public delegate void HelloDelegateSamp1(string strmsg);
    class Program
    {
        static void Main(string[] args)
        {
            HelloDelegateSamp1 s = new HelloDelegateSamp1(Hello);
            s("Welcome to delegate");
            Console.Read();
        }
        public static void Hello(string Message)
        {
            Console.WriteLine(Message);
        }
    }
We can pass n number of parameters/ Parameters is not required.
Without parameter: s();
N number of parameters: s(string strmsg, int age);
2.       Why we need delegate example-1
The following example is not a delegate. It is a simple example. But we will not reuse of Employee class in future. We can go for the delegate if we reuse the employee class.
Here we are promoted to employee with their experience. But some other company different criteria will use to promote employee. At this time this employee class does not help. We should change the logic. But without change the logic in employee (We have hard coded the logic here) class we can promote employee in different criteria using Delegate.
class Program
 {
  static void Main(string[] args)
   {
 List<Employee> emplist = new List<Employee>();
 emplist.Add(new Employee { ID = 101, Name = "GK", Salary = 5000, Experience = 5 });
 emplist.Add(new Employee { ID = 101, Name = "Len", Salary = 6000, Experience = 6 });
 emplist.Add(new Employee { ID = 101, Name = "Alex", Salary = 4000, Experience = 4 });
 emplist.Add(new Employee { ID = 101, Name = "Mani", Salary = 7000, Experience = 7 });
 emplist.Add(new Employee { ID = 101, Name = "Saj", Salary = 3000, Experience = 3 });
    Employee.promoteEmployee(emplist);
    Console.Read();
    }
 }
    class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void promoteEmployee(List<Employee> emplist)
        {
            foreach (Employee emp in emplist)
            {
                if (emp.Experience >= 5)
                {
                    Console.WriteLine(emp.Name);
                }
            }
        }
    }
3.       Why we need delegate example-2.
class Program
 {
  static void Main(string[] args)
   {
 List<Employee> emplist = new List<Employee>();
 emplist.Add(new Employee { ID = 101, Name = "GK", Salary = 5000, Experience = 5 });
 emplist.Add(new Employee { ID = 101, Name = "Len", Salary = 6000, Experience = 6 });
 emplist.Add(new Employee { ID = 101, Name = "Alex", Salary = 4000, Experience = 4 });
 emplist.Add(new Employee { ID = 101, Name = "Mani", Salary = 7000, Experience = 7 });
 emplist.Add(new Employee { ID = 101, Name = "Saj", Salary = 3000, Experience = 3 });

   //Create a instance of Delegate , Promote is method which has return type is bool
    IsPromotoble isPromotoble = new IsPromotoble(Promote);

   //  Employee.promoteEmployee(emplist, emp => emp.Experience >= 5);
   Employee.promoteEmployee(emplist, isPromotoble);
   Console.Read();
  }
       
//Delegate is reference to this method
        public static bool Promote(Employee emp)
        {
            if (emp.Experience >= 5)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
}
    
//Delegate Declaration
delegate bool IsPromotoble(Employee employee);
class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public int Salary { get; set; }
        public int Experience { get; set; }

        public static void promoteEmployee(List<Employee> emplist, IsPromotoble isElligibleToPromotoble)
        {
            foreach (Employee emp in emplist)
            {
                if (isElligibleToPromotoble(emp))
                {
                    Console.WriteLine(emp.Name + " Promoted");
                }
            }
        }
    }
Here we can promote the employee without modify the logic in employee class using the delegate. We can reuse the Employee class which it does not have the hard code logic.
Here instead of the below code, we can use lamda expression.
//Create a instance of Delegate, Promote is method which has return type is bool
    IsPromotoble isPromotoble = new IsPromotoble(Promote);

//Delegate is reference to this method
        public static bool Promote(Employee emp)
        {
            if (emp.Experience >= 5)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
}

lamda expression Example: instead of above code

 Employee.promoteEmployee(emplist, emp => emp.Experience >= 5);

4.  MultiCast Delegate


A multiple delegate is a delegate that has reference to the more than one function. When you invoke a multicast delegate, all the functions to the delegate is pointing to, are invoked.
There are to approaches to create a multicast delegate. Depending on the approach you use
+ or += to register a method  with  the delegate.
– or -= to register a method  with the delegate.
Note: A multicast delegate, invoke the methods in the invocation list, in the same order in which they are added.
If the delegate has a return type other than void and if the delegate is a multicast delegate, only the value of the last involved method will be returned. Along the same lines, if the delegate has an out parameter, the value of the output parameter, will be the value assigned by the last method.
Where do use multicast delegate?
Multicast delegate makes implementation of observer design pattern very simple. Observer pattern is also called as publish/ subscribe pattern.
Example 1,
public delegate void  SampleMulticastDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            SampleMulticastDelegate del1, del2, del3, del4;
            del1 = new SampleMulticastDelegate(Method1);
            del2 = new SampleMulticastDelegate(Method2);
            del3 = new SampleMulticastDelegate(Method3);
            del4 = del1 + del2 + del3;
            //del4 = del1 + del2 + del3 - del2;
            del4();  //Here del4 holding reference of 3 method.
            Console.Read();
        }
        public static void Method1()
        {
            Console.WriteLine("Method one is invoked");
        }
        public static void Method2()
        {
            Console.WriteLine("Method two is invoked");
        }
        public static void Method3()
        {
            Console.WriteLine("Method three is invoked");
        }         
    }  
Example 2,
Here the same instance but register the multiple methods using += sign.
static void Main(string[] args)
        {
            SampleMulticastDelegate del = new SampleMulticastDelegate(Method1);
            del += Method2;
            del += Method3;
     del -= Method2;  // Remove method 2 using - sign

           
            del();
            Console.Read();
        }
Example 3,  Here the return the values is 2. Reason- only the value of the last involved method will be returned
public delegate int SampleMulticastDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            SampleMulticastDelegate del = new SampleMulticastDelegate(Method1);
            del += Method2;

            int Delegateruturnval = del();
            Console.WriteLine("Delegate Return value is={0}", + Delegateruturnval);
            Console.Read();
        }
        public static int Method1()
        {
            return 1;
        }
        public static int Method2()
        {
            return 2;
        }
    }
Example 4, Here the return the values is 2. But we have used out parameter. Reason- only the value of the last involved method will be returned
public delegate void SampleMulticastDelegate(out int Integer);
    class Program
    {
        static void Main(string[] args)
        {
            SampleMulticastDelegate del = new SampleMulticastDelegate(Method1);
            del += Method2;

            int DelegateOutputvalue = -1;
            del(out DelegateOutputvalue);
            Console.WriteLine("Delegate Return value is={0}", +DelegateOutputvalue);
            Console.Read();
        }
        public static void Method1(out int number)
        {
            number = 1;
        }
        public static void Method2(out int number)
        {
            number = 2;
        }

    }