Tuesday, December 6, 2011

Tuple Class (.NET Framework 4)

Tuple Class (System.Tuple)

Web definitions
"A tuple (or n-tuple) is a fixed size collection of elements. Pairs, triples, quadruples etc. are tuples. In a programming language, a tuple is a data object containing other objects as elements. These element objects may be of different types."
"In mathematics, a tuple is a finite sequence (also known as an ordered list) of objects, each of a specified type. A tuple containing n objects is known as an n-tuple. For example the 4-tuple (or quadruple), with components of respective types PERSON, DAY, MONTH and YEAR, could be used to record that a certain person was born on a certain day of a certain month of a certain year."
"In set theory, an (ordered) n-tuple is a sequence (or ordered list) of n elements, where n is a positive integer. Tuples are usually written by listing the elements within parentheses "( )" and separated by commas; for example, (2,7,4,1,7) denotes a 5-tuple."
Introduction

A tuple is a data structure that has a specific number and sequence of elements of variety of types. 

The Tuple class does not itself represent a tuple. Instead, it is a factory class that provides static methods for creating instances of the tuple types that are supported by the .NET Framework. It provides helper methods that you can call to instantiate tuple objects without having to explicitly specify the type of each tuple component. You can also create an instance of a tuple class by calling its class constructor.

Tuple is a static class provides a Create method for creating the tuples of size 1-8. 
  • Tuple – Represents a tuple of size 1  
    • Create(T1)
  • Tuple – Represents a tuple of size 2 
    • Create(T1,T2)
  • Tuple – Represents a tuple of size 3 
    • Create(T1,T2,T3)
  • Tuple – Represents a tuple of size 4 
    • Create(T1,T2,T3,T4)
  • Tuple – Represents a tuple of size 5 
    • Create(T1,T2,T3,T4,T5)
  • Tuple – Represents a tuple of size 6 
    • Create(T1,T2,T3,T4,T5,T6)
  • Tuple – Represents a tuple of size 7 
    • Create(T1,T2,T3,T4,T5,T6,T7)
  • Tuple – Represents a tuple of size 8 or greater. 
    • Create(T1,T2,T3,T4,T5,T6,T7,T8)

Usage

Tuples are commonly used in four ways:
  • Represent a single set of data, a tuple can represent a database record.
  • Provide easy access to, and manipulation of, a data set. 
  • Using Tuple we can return multiple values from a method.
  • Similarly Tuple we can pass multiple values to a method through a single parameter. 
Example
 static void Main(string[] args) 
 { 
   // Create two-item tuple. Using constructors. 
   Tuple<int, string> tuple =
       new Tuple<int, string>(1, "Two Item Tuple"); 
  
   // Create two-item tuple. Using Create Method. 
   var tuple1 = Tuple.Create(1, "Two Item Tuple"); 
  
   // Access tuple properties. 
   Console.WriteLine("Tuple element 1: " + tuple.Item1); 
   Console.WriteLine("Tuple element 2: " + tuple.Item2); 
  
   //Try to set Item1 of tuple 
   //Error 1 Property or indexer 'System.Tuple<int,string>.Item1'
   //cannot be assigned to -- it is read only 
   //tuple.Item1 = 2; 
  
   Console.WriteLine("Tuple with two elements: "+tuple1); 
  
   //Create Tuples with element more than 8. Using constructors. 
   var tuple2 = new Tuple<string, int, int, int, int, int, int,
           Tuple<int, int, int, string>> 
         ("Number Items:", 1, 2, 3, 4, 5, 6, 
         new Tuple<int, int,int,string>(7, 8,9,"End of Items.")); 
  
  
   //Create Tuples with element more than 8. Using Create Method. 
   var tuple3 = Tuple.Create("Number Items:", 1, 2, 3, 4, 5, 6, 
   new Tuple<int, int, int, string>(7, 8, 9, "End of Items.")); 
  
  
  
   Console.WriteLine("Tuple with more than 8 elements: " + tuple3); 
        
   Console.ReadLine(); 
 }  
Output

Tuple element 1: 1
Tuple element 2: Two Item Tuple
Tuple with two elements: (1, Two Item Tuple)
Tuple with more than 8 elements: (Number Items:, 1, 2, 3, 4, 5, 6, (7, 8, 9, End
 of Items.))

Thursday, September 29, 2011

The Model-View-ViewModel (MVVM) Design Pattern


MVVM Pattern
The Model-View-ViewModel (MVVM) pattern helps you to cleanly separate the business and presentation logic of your application from its user interface (UI). Maintaining a clean separation between application logic and UI helps to address numerous development and design issues and can make your application much easier to test, maintain, and evolve. It can also greatly increase code re-use opportunities and allows developers and UI designers to collaborate more easily as they develop their respective parts of the application.

The MVVM pattern separates the UI of the application and the underlying presentation and business logic into three separate classes: the view, which encapsulates the UI and UI logic; the view model, which encapsulates presentation logic and state; and the model, which encapsulates the application’s business logic and data.

The MVVM pattern is a close variant of the Presentation Model pattern, optimized to take advantage of some of the core capabilities of WPF and Silverlight, such as data binding, data templates, commands, and behaviors.

In the MVVM pattern, the view encapsulates the UI and any UI logic, the view model encapsulates presentation logic and state, and the model encapsulates business logic and data. The view interacts with the view model through data binding, commands, and change notification events. The view model queries, observes, and coordinates updates to the model, converting, validating, and aggregating data as necessary for display in the view.

The following illustration shows the three MVVM classes and their interactions.


The MVVM classes and their interactions

 








As with all separated presentation patterns, the key to using the MVVM pattern effectively lies in understanding the appropriate way to factor your application’s code into the correct classes, and in understanding the ways in which these classes interact in various scenarios. The following sections describe the responsibilities and characteristics of each of the classes in the MVVM pattern.

The View Class

The view’s responsibility is to define the structure and appearance of what the user sees on the screen. Ideally, the code-behind file for a view contains only a constructor that calls the InitializeComponent method. In some cases, the code-behind file may contain UI logic code that implements visual behavior that is difficult or inefficient to express in Extensible Application Markup Language (XAML), such as complex animations, or the code needs to directly manipulate visual elements that are part of the view. You should not put any logic code in the view that you need to unit test. Typically, logic code in the view’s code-behind file will be tested by using a UI automation testing approach.

In Silverlight and WPF, data binding expressions in the view are evaluated against the view’s data context. In MVVM, the view’s data context is set to the view model. The view model implements properties and commands to which the view can bind and notifies the view of any changes in state through change notification events. There is typically a oneto-one relationship between a view and its view model.

Typically, views are Control-derived or UserControl-derived classes. However, in some cases, the view may be represented by a data template, which specifies the UI elements to be used to visually represent an object when it is displayed. Using data templates, a visual designer can easily define how a view model will be rendered or can modify its default visual representation without changing the underlying object itself or the behavior of the control that is used to display it.

Data templates can be thought of as views that do not have a code-behind file. They are designed to bind to a specific view model type whenever one is required to be displayed in the UI. At run time, the view, as defined by the data template, will be automatically instantiated and its data context set to the corresponding view model.

To summarize, the view has the following key characteristics:
• The view is a visual element, such as a window, page, user control, or data template.

• The view defines the controls contained in the view and their visual layout and styling.

• The view references the view model through its DataContext property. The controls in the view are data bound to the properties and commands exposed by the view model.

• The view may customize the data binding behavior between the view and the view model. For example, the view may use value converters to format the data to be displayed in the UI, or it may use validation rules to provide additional input data validation to the user.

• The view defines and handles UI visual behavior, such as animations or transitions that may be triggered from a state change in the view model or by the user’s interaction with the UI.

• The view’s code-behind file may define UI logic to implement visual behavior that is difficult to express in XAML or that requires direct references to the specific UI controls defined in the view.

The View Model Class

The view model in the MVVM pattern encapsulates the presentation logic and data for the view. It has no direct reference to the view or any knowledge about the view’s specific implementation or type. The view model implements properties and commands to which the view can bind data and notifies the view of any state changes through change notification events. The properties and commands that the view model provides define the functionality to be offered by the UI, but the view determines how that functionality is to be rendered.

The view model is responsible for coordinating the view’s interaction with any model classes that are required. Typically, there is a one-to many-relationship between the view model and the model classes. The view model might expose model classes directly to the view so that controls in the view can bind data directly to them. In this case, the model classes will need to be designed to support data binding and the relevant change notification events.

The view model may convert or manipulate model data so that it can be easily consumed by the view. The view model may define additional properties specifically to support the view. These properties would not normally be part of (or could not be added to) the model. For example, the view model may combine the value of two fields to make it easier for the view to be presented, or it may calculate the number of characters remaining for input in fields with a maximum length. The view model may also implement data validation logic to ensure data consistency.

The view model may define logical states the view can use to provide visual changes in the UI. The view may define layout or styling changes that reflect the state of the view model. For example, the view model may define a state that indicates that data is being submitted asynchronously to a web service. The view can display an animation while it is in this state to provide visual feedback to the user.
Typically, the view model will define commands or actions that can be represented in the UI and that the user can invoke. A common example is when the view model provides a Submit command that allows the user submit data to a web service or to a data repository.

The view might represent that command with a button so that the user can click the button to submit the data. Typically, when the command becomes unavailable, its associated UI representation becomes disabled. Commands provide a way to encapsulate user actions and to cleanly separate them from their visual representation in the UI.

To summarize, the view model has the following key characteristics:
• The view model is a non-visual class and does not derive from any WPF or Silverlight base class. It encapsulates the presentation logic required to support a use case or user task in the application. The view model is testable independently of the view and the model.
• Typically, the view model does not reference the view directly. It implements properties and commands to which the view can bind data. It uses the INotify PropertyChanged and INotifyCollectionChanged interfaces to generate change notification events that notify the view of any state changes.
• The view model coordinates the view’s interaction with the model. It may convert or manipulate data so that it can be easily consumed by the view, and it might implement additional properties that may not be present on the model. It may also use the IDataErrorInfo or INotifyDataErrorInfo interfaces to implement data validation.
• The view model may define logical states that the view can represent visually to the user.

The Model Class

The model in the MVVM pattern encapsulates business logic and data. Business logic is defined as any application logic that is concerned with the retrieval and management of application data and with making sure that any business rules that ensure data consistency and validity are imposed. To maximize re-use opportunities, models should not contain any use case–specific or user task–specific behavior or application logic.

Typically, the model represents the client-side domain model for the application. It can define data structures based on the application’s data model and any supporting business and validation logic. The model may also include the code to support data access and caching, although in most cases, a separate data repository or service is employed for this. Often, the model and data access layer are generated as part of a data access or service strategy, such as the ADO.NET Entity Framework, WCF Data Services, or WCF RIA Services.

Typically, the model implements the facilities that make it easy to bind to the view. This usually means that it supports property and collection changed notification through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. Models classes that represent collections of objects typically derive from the ObservableCollection class, which provides an implementation of the INotifyCollectionChanged interface.

The model may also support data validation and error reporting through the IData ErrorInfo (or INotifyDataErrorInfo) interfaces. These interfaces allow WPF and Silverlight data binding to be notified when values change so that the UI can be updated. They also enable support for data validation and error reporting in the UI layer.

The model has the following key characteristics:
• The model classes are non-visual classes that encapsulate the application’s data and business logic. They are responsible for managing the application’s data and for ensuring its consistency and validity by encapsulating the required business rules and data validation logic.
• The model classes do not directly reference the view or view model classes and have no dependency on how they are implemented.
• The model classes typically provide property and collection change notification events through the INotifyPropertyChanged and INotifyCollectionChanged interfaces. This allows them to be easily data bound in the view. Model classes that represent collections of objects typically derive from the ObservableCollection class.
• The model classes typically provide data validation and error reporting through either the IDataErrorInfo or INotifyDataErrorInfo interfaces.
• The model classes are typically used in conjunction with a service or repository that encapsulates data access and caching.

Tuesday, September 20, 2011

Silverlight ListBoxItem Double Click Event

Following is the Code snippet for the List Box Item double click event using Silverlight 4:

XAML (MainPage.Xaml):
CODE(MainPage.Xaml.cs):

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Browser;
using System.Windows.Input;
namespace ListBoxDoubleClick
{
    public partial class MainPage : UserControl    {
        Point _clickPosition;
        public DateTime _lastClick = DateTime.Now;
        private bool _firstClickDone = false;
        public MainPage()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }
        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            for (int i = 1; i < 11; i++)
            {
                ListBoxItem lbitem = new ListBoxItem();
                lbitem.Name = "lb_" + i;
                lbitem.Content = "This is ListBoxItem No:" + i;
                lbitem.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(ListBoxItem_DoubleClickEvent), true);
                listBox1.Items.Add(lbitem);
            }
        }
        private void ListBoxItem_DoubleClickEvent(object sender, MouseButtonEventArgs e)
        {
            ListBoxItem element = sender as ListBoxItem;
            if (element == null)
                return;
            DateTime clickTime = DateTime.Now;
            TimeSpan span = clickTime - _lastClick;       
            if (span.TotalMilliseconds > 300 || _firstClickDone == false)
            {
                //Single Click                lblMsg.Content = string.Format("ListBoxItem \" {0}\" is Single clicked. ", element.Content );
                _clickPosition = e.GetPosition(element);
                _firstClickDone = true;
                _lastClick = DateTime.Now;
            }
            else            {
                Point position = e.GetPosition(element);
                //Double Click                if (Math.Abs(_clickPosition.X - position.X) < 4 && Math.Abs(_clickPosition.Y - position.Y) < 4) //mouse didn't move => Valid double click                {
                    lblMsg.Content = string.Format("ListBoxItem \" {0}\" is Double clicked. ", element.Content);
                    /// Your logic goes here for double click event                    ///                 }
           
                _firstClickDone = false;
            }
        }
    }
}
SAMPLE OUTPUT: 






SOURCE DOWNLOAD LINK: 
ListBox Double Click







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.