Tuesday 24 September 2013

Delegates - C Sharp

A delegate is a type safe function pointer.That is, they hold reference(Pointer) to a function. 

The signature of the delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error. This is the reason delegates are called as 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 is to this function the delegate will point to.

Declaration:
A delegate is declared by using the keyword delegate, otherwise it resembles a method declaration.
delegate int delegateAdd(int xint y);

Instantiation:
To create a delegate instance, we need to assign a method (which has same signature as delegate) to delegate.

        static int add(int aint b)
        { 
          return a + b
        }

        //create delegate instance
        delegateAdd objAdd = new delegateAdd(Add);

        //short hand for above statement
        delegateAdd objAdd = Add;

Invocation:
     // Invoke delegate to call method
     int result = objAdd.Invoke(36);

     //short hand for above statement
     int result = objAdd(36); 
Invoking a delegate is like as invoking a regular method.

Complete Code is:
class Program
{
        delegate int delegateAdd(int xint y);

        static int add(int aint b)
        { return a + b; }

        static void Main(string[] args)
        {
           // Program p = new Program();
           //delegateAdd _del = p.add;
            delegateAdd _del = add;
            int result = _del.Invoke(36);
            Console.Write(result);
            Console.Read();
        }
}

Output will be : 9

Type of Delegate
Delegates are one of two types:
  1. Singlecast Delegate
  2. Multicast Delegate
Singlecast DelegateA Singlecast delegate is derived from the System.Delegate class. It can contain a reference for one method at a time. In the above example the delegate uses a Singlecast delegate.

Multicast DelegateA Multicast delegate is derived from the System.MulticastDelegate class. It can contain references for multiple methods. For understanding multicast delegates you can consider the real-life example: of a Coffee vending machine.

A Coffee vending machine has three containers for Milk, Coffee, and Tea. If you press the Tea button then there will two containers, Milk and Tea that work together. And if you press the button for Coffee then the Milk and Coffee containers will work. So if you want to call multiple functions then you can use a multicast delegate.

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

namespace Anonymous
{
    class Class1    {
        public delegate void Vender();

        public static void Milk()
        {
            Console.Write("Milk + ");
        }
        public static void Tea()
        {
            Console.Write("Tea = Tea ");
        }
        public static void Coffee()
        {
            Console.Write("Coffee = Coffee ");
        }

        static void Main()
        {
            Vender vender = new Vender(Milk);
            Console.WriteLine("\t\tPress 1 For Tea\n\t\t Press 2 For Coffee");
            int Opt = Convert.ToInt32(Console.ReadLine());
            switch (Opt)
            {
                case 1:
                    vender += Tea;
                    break;

                case 2:
                    vender += Coffee;
                    break;

                default:
                    Console.WriteLine("Invalid Option !");
                    Environment.Exit(0);
                    break;
            }

            vender();
            Console.ReadKey();
        }
    }
}
In the above program I just created the three functions, Tea, Coffee and Milk. When one is pressed there will be two functions, called Milk and Tea. If the user chooses both then again the two functions, Milk and Coffee are called. Since Milk is common to both situations I just pass Milk in the Delegate parameter. And the delegate understands "+" and "+=" for adding references of functions and "-" and "-=" for removing function references, so depending on the option used I just add a function reference with the same Delegate object vendor. And invoke the delegate vendor.
Remember, multicasting of delegate should have a return type of Void otherwise it will throw a runtime exception.
Anonymous Method In C# 1.0 you can use a delegate and pass a function reference with an initializing delegate with a function name, but C# 2.0 introduced anonymous functions.

Creating an anonymous method as an inline block of code to be passed as a delegate parameter can be done as you see in the 
following: 


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

namespace Anonymous
{
    class Class1    {
        public delegate void Del();

        static void Main(string[] args)
        {
            Del obj = delegate() {
                Console.WriteLine"Class1.fun");
            };

            obj();
        }
    }
}
Use of an anonymous function can reduce the lines of code. So, here in the program above you can see I just passed a block of code for a delegate parameter inside of creating a function anywhere else and passing the function name. The anonymous function uses the delegate keyword while delegate initialization writes a block of code. You can also pass a parameter for an anonymous function as follows:

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

namespace Anonymous
{
    class Class1    {
        public delegate void Delstring Mesg);

        static void Main(string[] args)
        {
            Del obj = delegate(string Mesg) {
                Console.WriteLine(Mesg);
            };

            obj("Class1.fun");
        }
    }
}
Note:
You cannot use goto, break and continue statements inside the anonymous method block if the targat is outside an anonymous block.
Difference between Delegate and Event


Continue Reading →

Thursday 19 September 2013

RANK() and DENSE_RANK() - SQL Server

 The RANK() function in SQL Server returns the position of a value within the partition of a result set, with gaps in the ranking where there are ties.

The DENSE_RANK() function in SQL Server returns the position of a value within the partition of a result set, leaving no gaps in the ranking where there are ties.


These functions also enumerate rows as ROW_NUMBER() function, but a somewhat different way. Difference is that the rows, that have the same values in column on which you are ordering, receive the same number (rank). For example, the values (ordered in ascending)











will have such numbers:

The question arises as from what numbers will continue numbering if, say, in a sequence of numbers will appear on 7 and so on? There are two variants:

1) number 4, because it is the following number in sequence;
2) number 6, because next line will be the sixth.

This "ambiguity" has led to the appearance of two functions instead of one - RANK and DENSE_RANK, the first of which will continue the numbering from 6 and the second (dense) - with 4.

Let's consider some examples. We begin from showing the differences in the behavior of functions RANK and ROW_NUMBER:


Execute

SELECT *, ROW_NUMBER() OVER(ORDER BY type) num,
RANK() OVER(ORDER BY type) rnk    FROM Printer;

Here the values of compared functions are outputs in two last columns with row ordering in column ‘type’:

2
1433
y
Jet
270.00
   1
  1
3
1434
y
Jet
290.00
   2
  1
1
1276
n
Laser
400.00
   3
  3
6
1288 
n
Laser
400.00
   4
  3
4
1401
n
Matrix
150.00
   5
  5
5
1408
n
Matrix
270.00
   6
  5
As expected ROW_NUMBER enumerates entire set of rows returned by the query. RANK function work on the second of the above variant, i.e. the line number will be the following number after rows with an identical rank.

Now compare the "dense" and "nondense" rank: 

  Execute
SELECT *, RANK() OVER(ORDER BY type) rnk,
DENSE_RANK() OVER(ORDER BY type) rnk_dense FROM Printer;


It should also draw attention to the order in which output rows of the result set. Because SELECT statement in our example does not have ORDER BY clause and same ordering by column ‘type’ is used to rank calculating, then the result is displayed in the same manner. In order to optimize if you don’t need any other ordering the result set; use this fact in order not to perform additional sorting, which decrease the performance of the query.

As well as for ROW_NUMBER function, PARTITION BY can be used in OVER clause, it divides the entire set of rows returned by the query to groups to which then the appropriate function is applied.
The query
SELECT *, RANK() OVER(PARTITION BY type ORDER BY price) rnk FROM Printer;

allows the ranking of models by prices in ascending order in each group defined by printer type:

2
1433
y
Jet
270.00
1
3
1434
y
Jet
290.00
2
1
1276
n
Laser
400.00
1
6
1288
n
Laser
400.00
1
4
1401
n
Matrix
150.00
1
5
1408
n
Matrix
270.00
2

And here so it is possible to select the cheapest models from each category:

SELECT model, color, type, price FROM ( SELECT *, RANK() OVER(PARTITION BY type ORDER BY price) rnk FROM Printer) Ranked_models WHERE rnk = 1;

1433
y
Jet
270.00
1276
n
Laser
400.00
1288
n
Laser
400.00
1401
n
Matrix
150.00
The query could be shorter, if the RANK function could be used in a WHERE clause, since own value of the rank we do not need. However, it is forbidden (as for other ranking functions), at least in SQL Server.

Finally, consider another example.
Example. Find makers who produce more than 2 models of PC.

This task has a solution through the traditional aggregate functions

SELECT maker FROM Product
      WHERE type = 'PC'
      GROUP BY maker
      HAVING COUNT(*) > 2;

However, this task can be solved by using the RANK function. The idea is as follows: to rank the models of each maker's on a unique key and to select only those manufacturers, whose products reach the rank 3:

      SELECT maker
      FROM (
      SELECT maker, RANK() OVER(PARTITION BY maker ORDER BY model) rnk
      FROM Product
      WHERE type = 'PC') Ranked_makers
      WHERE rnk = 3;

Both in one, and in another case, of course, we get the same result:

Once again: in last case, ordering must be performed on unique column combination, because, otherwise, it can be exists over 3 models but rank under 3 (for example 1, 2, 2, …). In our case, this condition is satisfied, because ordering is performed by the column ‘model’, which is the primary key in table Product.

By the way, the execution plans of these queries show the same cost of most costly operations - a table scan and sort (which in first case, there is an implicit, and called by the grouping operation).


Continue Reading →

Fault Contract in WCF

What is fault Contract?

A Fault Contract is a way to handle an error/exception in WCF. In C# we can handle the error using try and catch blocks at the client side. The purpose of a Fault Contract is to handle an error by the service class and display in the client side. Whenever the client makes a call to a service class and an unexpected exception comes such as, SQL Server is not responding, or Divide by zero; in this case the service class throws an exception to the client using the Fault Contract. 

By default when we throw an exception from a service, it will not reach the client. WCF provides the option to handle and convey the error message to the client from a service using a SOAP Fault Contract.

To support SOAP Faults, WCF provides the FaultException class. This class has two forms:
  1. FaultException: to send an untyped fault back to the caller
  2. FaultException<T>: to send a typed fault data to the client. It is basically a Generic Type.
Syntax 
[OperationContract]
[FaultContract(typeof(MyException))]
string getDetails(int value);

The Fault Contract sample demonstrates how to communicate error information from a service to a client. The sample is based on the, with some additional code added to the servie to convert an internal exception to a fault.
Now we are going to implement the Fault Contract .
Create a new Project . add  WCF Application Project. the Code are :

using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace FaultContractApp
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract (typeof(CustomException))]
        int add(int num1int num2);
    }

    [DataContract()]
    public class CustomException
    {
        [DataMember()]
        public string Title;

        [DataMember()]
        public string ExceptionMessage;

        [DataMember()]
        public string InnerException;

        [DataMember()]
        public string StackTrace;
    }


using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace FaultContractApp
{
    public class Service1 : IService1
    {

        public int add(int num1int num2)
        {
            CustomException _fault = new CustomException();
            _fault.ExceptionMessage = "Exception occured in the service!";
            _fault.InnerException = "Inner EXception";
            _fault.Title = "Exception Title";
            _fault.StackTrace = "Stack Trace message from service.";
            throw new FaultException<CustomException>(_fault,"Reason: Testing the Fault contract");
        }
    }
}


now add a new Console Project in your Solution. add the ServiceReference in your Console Project .
now write the Code to use Service . the Code are :

using System.ServiceModel;
using myConsole.ServiceReference1;

namespace myConsole
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1Client _service = new Service1Client();
            try
            {
                int result = _service.add(1155);
                Console.WriteLine(result);
                Console.ReadLine();
            }
            catch (FaultException<CustomExceptionex)
            {
                Console.WriteLine(string.Format("Title ->  {0} "ex.Detail.Title));
                Console.WriteLine(string.Format("ExceptionMessage ->  {0} "ex.Detail.ExceptionMessage));
                Console.WriteLine(string.Format("Inner Exception ->  {0} "ex.Detail.InnerException));
                Console.WriteLine(string.Format("StackTrace ->  {0} "ex.Detail.StackTrace));
                Console.ReadLine();
            }
        }
    }
}

Now debug the Console Application. you will get the Fault Exception generated by Service end.



the Complete Demo Project is attached: Click me!

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives