Thursday, July 21, 2011

WPF Routed Event

Routed Events


Functional definition: A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event.

Implementation definition: A routed event is a CLR event that is backed by an instance of the RoutedEvent class and is processed by the Windows Presentation Foundation (WPF) event system.
A particular event feature that is fundamental to WPF is a routed event. Routed events enable an element to handle an event that was raised by a different element, as long as the elements are connected through a tree relationship. When specifying event handling with a XAML attribute, the routed event can be listened for and handled on any element, including elements that do not list that particular event in the class members table. This is accomplished by qualifying the event name attribute with the owning class name. For instance, the parent StackPanel containing Button could register a handler for the child element button's Click event by specifying the attribute Button.Click on the StackPanel object element, with your handler name as the attribute value.

See for e.g. the XAML below contains the StackPanel as a parent element and in the hierarchy contains the button element thus forms a VisualTree (StackPanel ---- Button):
 <StackPanel>  <Button Content="Click Me" Click="btn_Clicked"/> </StackPanel>
void btn_Clicked (object sender, RoutedEventArgs args)
{  //logic to handle the Click event }
  
Common handler for all the buttons contained within the StackPanel:

  <StackPanel Background="LightGray" Orientation="Horizontal" Button.Click="CommonClickHandler">    <Button Name="YesButton" Width="Auto" >Yes</Button>    <Button Name="NoButton" Width="Auto" >No</Button>    <Button Name="CancelButton" Width="Auto" >Cancel</Button>  </StackPanel>
     void CommonClickHandler (object sender, RoutedEventArgs args)
    {
  //logic to handle the Click event  FrameworkElement feSource = e.Source as FrameworkElement;
  switch (feSource.Name)
  {    case "YesButton":
      // do something here ...      break;
    case "NoButton":
      // do something ...      break;
    case "CancelButton":
      // do something ...      break;
  }  e.Handled=true; } 

In WPF, there are three types of event notification methods, namely:
Bubbling: Allows events to bubble up the VisualTree (the tree of Visual UI Elements), to the root element.

Tunneling: Allows events to tunnel down the VisualTree.

Direct: Works just like the old .NET 1.x/2.0 CLR events. Only the subscriber gets to see the event.

Figure 1: VisualTree showing Bubbling and Tunneling



What actually happens is that when an event is raised, it travels up and down the VisualTree, invoking any handlers that are subscribed to the RoutedEvent. This traversal of the VisualTree will not be the entire tree, but rather the portion of the tree that is directly related to the element that raised the event.

Naming Conventions
 There is a naming convention in place to aid in determining how these events were created.
Tunneling events usually start with "PreviewXXX" and Bubbling events are usually just XXX.
 For example, PreviewKeyDown (Tunneling) and KeyDown (Bubbling).




References: 
For more details see MSDN source. Also see Post By Sacha Barber.


Wednesday, July 13, 2011

Func Type

Func Type
        You can use the Func delegate to pass a method as a parameter without explicitly declaring a custom delegate.You can use this delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and that it must return a value.
Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.
Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace FuncTest
{
    public class Customer
    {
       public static Func<List<Customer>, int>CompletedFunc{ get
          set; }
        public string Name;
        public string City;
 
        public Customer()
        { }
        public Customer(string name, string city)
        {
            Name = name;
            City = city;
        }
        public static void DisplayCustomers()
        {
           List<Customer> cutomerList = new List<Customer>();
           cutomerList.Add(new Customer("Junaid Ahmed""Karachi"));
           cutomerList.Add(new Customer("Asif Mughal""Sukkur"));
           cutomerList.Add(new Customer("Ali Khan""Lahore"));
 
          if (CompletedFunc != null)
           //Func return int in this case
           Console.WriteLine("The number of customers in list are :"                         + CompletedFunc.Invoke (cutomerList));
        }
 
    } 
 
    class Program
    {
 
       public static void PrintCustomers(List<Customer> customers)
       {
          foreach (Customer customer in customers)
          {
             Console.WriteLine(
                 string.Format("Customer Name : {0}  City : {1}",
 customer.Name, customer.City));
          }
       }
       static void Main(string[] args)
       {
          // 1). You can print like this by assigning the Func                           //delegate with anonymous methods in C#        
          Customer.CompletedFunc = delegate(List<Customer>
 listCustomer)
          {
              PrintCustomers(listCustomers);
              return listCustomers.Count;
          };
          // 2). You can print like this by assigning a lambda 
          //expression to a Func delegate instance
          //Customer.CompletedFunc = (listCustomers) =>
          //{
          //    PrintCustomers(listCustomers);
          //    return listCustomers.Count;
          //};
           
          Customer.DisplayCustomers();
 
           Console.ReadLine();
       }
    }
 
}
 
Output:
  
Customer Name : Junaid Ahmed  City : Karachi
Customer Name : Asif Mughal  City : Sukkur
Customer Name : Ali Khan  City : Lahore
The number of customers in list are : 3


 See msdn for details.
 

Action Type

Action Type
        You can use the Action delegate to pass a method as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate. This means that the encapsulated method must have one parameter that is passed to it by value, and it must not return a value. (In C#, the method must return void.) Typically, such a method is used to perform an operation.
     Encapsulates a method that has a single parameter and does not return a value.

Example:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
 
namespace ActionTest
{
    public class Customer
    {
       public static Action<List<Customer>> 
CompletedAction {get;set;}
        public string Name;
        public string City;
 
        public Customer()
        { }
        public Customer(string name, string city)
        {
            Name = name;
            City = city;
        }
        public static void DisplayCustomers()
        {
           List<Customer> cutomerList = new List<Customer>();
           cutomerList.Add(new Customer("Junaid Ahmed""Karachi"));
           cutomerList.Add(new Customer("Asif Mughal""Sukkur"));
           cutomerList.Add(new Customer("Ali Khan""Lahore"));
         
            if(CompletedAction !=null)
                CompletedAction(cutomerList);
        }
 
    }
 
 
    class Program
    {     
 
        public static  void PrintCustomers(List<Customer> customers)
        {
            foreach (Customer customer in customers)
            {
                Console.WriteLine(
                 string.Format("Customer Name : {0}  City : {1}",
                       customer.Name, customer.City));
            }
        }
        static void Main(string[] args)
        {           
 
            // 1). You can print like this by assigning the Action
            // delegate with anonymous methods in C#
            Customer.CompletedAction =  
                  delegate(List<Customer> listCustomers) 
            {
                PrintCustomers(listCustomers);
            };
 
 
            // 2). You can print like this by assigning a
            // lambda expression to an Action delegate instance
            //Customer.CompletedAction = (listCustomers) =>
            //{
            //    PrintCustomers(listCustomers);
            //};
            //OR you can use this one same as 2.
            //Customer.CompletedAction = 
                  // listCustomers => PrintCustomers(listCustomers);
 
            Customer.DisplayCustomers();
       
            Console.ReadLine(); 
        }
    }
}
 
 
Output: 
Customer Name : Junaid Ahmed  City : Karachi
Customer Name : Asif Mughal  City : Sukkur
Customer Name : Ali Khan  City : Lahore



See msdn for details.

Wednesday, July 6, 2011

UML Relationship

UML Relationships
In an ER diagram for two entities A and B, we can show only one type of relationship–a Relational relationship–which means that entity A is somehow related to entity B. But in a class diagram, the relationships can be further divided on the basis of object-oriented principles such as inheritance, association, and so on. The following sections describe the main UML relationships used in a class diagram.

1. Dependency Relationship:  A Dependency exists between two elements if changes to one element will affect the other. A dependency relationship is the simplest relationship of all, and means that Entity 1 depends on Entity 2 in such a way that any change in entity 2 might break entity 1.                            
Dependency relationships are represented by a broken (dashed) line with an "empty" arrow (--->). The direction of this arrow flows to the entity that is dependent on the entity that the arrow flows from. 

2. Association Relationship: An Association shows the relationship between instances of classes. An association is similar to a dependency except that it specifies the relationship in a stricter form. In its basic form, it is represented by a solid arrow (instead of dashed as in a dependency relationship).

An Association relationship can be divided further into two separate relationships,based on the state of the aggregated object in the dependent class.
a). Aggregation

An Aggregation relationship depicts a classifier as a part of, or as subordinate to, another classifier. For example, if Entity1 goes out of scope, it does not mean that Entity2 has to go out of scope too. That is, the lifetime of Entity2 is not necessarily controlled by Entity1. An aggregation is represented by a straight arrow, with an empty diamond at the tail, as shown in the following figure:


So, in our example, Entity2 is a part of (or subordinate to) Entity 1. If you destroy the parent class (Entity 1) in an aggregation (weak) relationship, the child class (Entity 2) can survive on its own.

Let's understand aggregations by using our example of the Order Management System. Consider the OrderLine and Product classes. An OrderLine can have multiple quantities of one Product. If an OrderLine is destroyed, it does not mean that we delete the Product as well. A Product can exist independently of the OrderLine object. Here is the relationship diagram between OrderLine and Product classes:


In the diagram, we can see an Aggregation relationship between OrderLine and Product classes. Put simply, the above diagram states that if an order is cancelled, all of the products will not be destroyed; they will only be "de-associated" from that particular order.
b). Composition

A Composition is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. For example: You have a 'student' who has a 'schedule'. If you destroy the student, the schedule will cease to exist. In this case, the associated entity is destroyed when the parent entity goes out of scope. Composition is represented by a straight arrow with a solid diamond at the tail, as shown below.



In our case, Entity-2 is controlled by Entity-1. If Entity 1 is destroyed in a composition (strong) relationship, Entity-2 is destroyed as well.

Let's understand compositions by using our example of the Order Management System. Consider the Customer and Order classes. A Customer can have one or more orders, and an Order can have one or more Products (in order lines). An Order object cannot exist on its own without a Customer. So the following Composition indicates that if a Customer object goes out of scope, the Orders associated with that Customer go out of scope too.

 
3. Generalization Relationship: Inheritance is a very widely known and common feature of OOP. In UML, inheritance is depicted using generalization relationships, depicted by a straight arrow with a hollow arrowhead (triangle) at one end. A generalization relationship (also known as a "is-a" relationship) implies that a specialized (child) class is based on a general (parent) class. Here is a diagram illustrating this:


Here, we can see that the arrow points in the direction of the base class. In our Order Management System, we can have a base class for all customers; we can call it Person class so that we have other classes derived from it, such as Customer, CSR (Customer Sales Representative), and so on.


4). Realization Relationship: Realization is similar to generalization but depicts the relationship between an interface and a class implementing that interface. In UML, realization is depicted with a dashed arrow with a hollow arrowhead (triangle) at one end. A realization relationship exists between the two classes when one of them must realize, or implement, the behavior specified by the other.

For example, a realization relationship connects an interface to an implementing class. The interface specifies the behaviors, and the implementing class implements the behaviors. Here is a diagram illustrating this:



Here, we can see that the arrow points in the direction of the interface. Note that the italicized text in entities that are interfaces. It is UML convention to italicize interfaces.