Wednesday, March 24, 2010

Advantages of WPF

Advantages of WPF:

1. Broad Integration: Prior to WPF, it was very difficult to use 3D, Video, Speech, and rich document viewing in addition to normal 2D Graphics and controls would have to learn several independent technologies. WPF covers all these with consisting programming model as well as tight integration when each type of media gets composited and rendered.

2. Resolution Independence: WPF applications are device independent i.e., smart client applications. Like normal applications it won’t get decrease the size as the resolution gets increase. This is possible because WPF emphasis on vector graphics.

3. Hardware Acceleration: WPF is built on top of Direct 3D, content in a WPF application whether 2D or 3D, Graphics or text is converted to 3D triangles, textures and other Direct 3D objects and then rendered by hardware. WPF applications can get the benefit of hardware acceleration for smoother graphics and all round better performance.

4. Declerative Programming: WPF takes the declarative programming to the next level with the introduction of Extensible Application Markup Language(XAML), pronounced as “Zammel”.
XAML is like HTML in web used for creating the interface, resulting graphical designers are empowered to contribute directly to the look and feel of applications.

5. Rich Composition and Customization: WPF controls are extremely compostable.
Eg: we can create combo box with animated buttons.

6. Easy Deployment: WPF build on top of ClickOnce for supporting direct integration with web browser and it’s navigation system.

Fundamentals of WPF -1

User Interface is evolved from dos based interface to windows based and now microsoft has introduced the new user interface developement methodology which is called as WPF.

Until introduction of WPF, We have application in which we primarily considered the functional aspect while the user experience takes the backseat, but now with the invention of WPF we can create rich user experience in our application. Rich user experience does not mean you load lot of bulky graphics on the user interface but it does mean that user interface you design should be user friendly so that user should be more than satisfied interacting with user interface. With the help of WPF separation of designing and developing of user interface can be easily achieved. WPF integrates application UIs, 2D graphics, 3D graphics, documents and multimedia into one single unit. Its vector based rendering engine uses hardware acceleration of modern graphic cards. This makes the UI faster, scalable and resolution independent.

There are four tools available for designer to develop the UI. These tools does have more graphics development support than Microsoft visual studio.

This tool suite is called Microsoft Expression. It consists of the four products:

Expression Blend is built to create user interfaces in WPF and Silverlight. It builds the bridge between designer and developers. VisualStudio solutions can be open from this.
Expression Design is a lightweight version of Adobe Illustrator to create and edit vector graphics.
Expression Media is built to encode, cut and enrich video files and optimize them for silverlight streaming
Expression Web is Microsoft next generation of HTML and Javascript editor.

Development method of WPF consist of following steps


1)Requirement Analysis
In this step business analyst takes the requirement and does the analysis to prepare use case and scenarios it is the iterative process between analyst and user which will clear exact need of the user.
2)Creation of prototype
From the use cases and scenarios one can develop raw prototype again this is also iterative process as designer , analyst and user is involved in this. Prototypes can be developed on paper, with MS Visio , with expression blend – sketch flow , or real application with dummy data
3)Implementation of business logic
In this step business logic implementation has been done by the developers
4)Integration
In this step integration of business logic with the user interface has been done.
5)Test
This step is a final testing phase in which testers will do testing to test all aspect of the application.

WPF separates appearance of application with its behavior. Appearance is completely defined in the XAML(Extendable markup language) and behaviors implemented using various languages like C# and visual basic. Appearance and behavior relates each other by events and command. Like HTML Graphical design tool can be managed with simple XAML instead of compiling a code. WPF controls are highly composable. It is XAML file so we can compose it easily. We can define almost any type of controls as content of another.

WPF Fundamentals

WPF Fundamentals

WPF has some important new concepts that are beyond of what most .NET developers know from WinForms. But its very useful to understand these concepts before you start developing WPF applications.
XAML

XAML stands for Extensible Application Markup Language. Its a simple language based on XML that was invented for WPF to create and initialize user interface elements. The idea is similar to HTML.


Logical and Visual Tree
User interface elements in WPF have a hierachical relation. This is called the visual tree. A user interface element is composed of multiple parts. If you build a tree including all controls parts you have the logical tree.


Layouts:-
StackPanel
The StackPanel is a simple and useful layout panel. It stacks its child elements below or beside each other, dependening on its orientation. This is very useful to create any kinds of lists. All WPF ItemsControls like ComboBox, ListBox or Menu use a StackPanel as their internal layout panel.


Code:-

How do you like your coffee?
Black
With milk
Latte machiato
Chappuchino


Stack Items horizontally
A good example for a horizontal stack panel are the "OK" and "Cancel" buttons of a dialog window. Because the size of the text can change if the user changes the font-size or switches the language we should avoid fixed sized buttons. The stack panel aligns the two buttons depending on their desired size. If they need more space they will get it automatically. Never mess again with too small or too large buttons.
Code:-


OK
Cancel

WPF Grid Layout Panel
The grid layout panel is the most powerful layout panel in WPF because its so flexible and universal in use. Thats the reason why Visual Studio adds a Grid layout control as root element by default to each Window or Page.
The grid layout defines a set of columns and rows. Each side of a control that has been added to the grid layout can now be bound to one of the row or colum with an optional margin.
Code:-













Row:0 Col:0
Row:1 Col:1
Row:2 Col:2
Row:2 Col:2



Sizing rows and columns
The size of a row or a column can be defined in the following types
• Fixed size of logical units (wpf pixels)
• Auto takes as much space as needed by contained controls
• Star (*) takes as much space as possible, percentally split over all star columns. Like percentage in a HTML table except that the sum of all relative columns does not have to be 100

WPF Timer (DispatcherTimer)

This article discusses the WPF DispatcherTimer.

Most of us are from a background of C# (or VB.Net). You must have some point of time come across a scenario for performing a repetitive GUI operation after certain period of time. The solution in most cases has been the WinForm's Timer.

What about WPF ? Does it have a Timer ?

WPF no different to WinForm has it's own Timer equivalent. It is called DispatcherTimer. There are other options to get the Timer behavior but one of the most efficient for a Window based operation is the DispatcherTimer.

I have attached a sample Timer application demonstrating the functionality.

The window has a "Start timer" and "Stop timer" functionality. There is an input TextBox which takes the Timer frequency in milliseconds.

Just enter the Timer frequency in millisecond and hit the "Start timer" button. There is a status bar which displays the status of the time. At start it will be blank. When you start the Timer it will display the current Time and when you stop the Timer it will display the "Stopped" status.

Let us discuss the code to look into how we use it.

XAML,
< Window x:Class="TimerSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Timer" Height="148" Width="300" ResizeMode="NoResize" 
WindowStartupLocation="CenterScreen">
    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal">
            <Label Margin="50,5,5,5">Timer value:</Label>
            <TextBox Name="time"  Height="20">1000</TextBox>
            <Label Margin="0,5,5,5" FontWeight="Bold">ms</Label>
        </StackPanel>
        <StackPanel Orientation="Horizontal">
            <Button Margin="50,5,5,5" Click="Start_Click">Start timer</Button>
            <Button Margin="5,5,75,5" Click="Stop_Click">Stop timer</Button>
        </StackPanel>
        <TextBlock Name="status"  Margin="0,35,0,0" Background="LightGray"
 Height="20" Padding="25,0,0,0">Not working</TextBlock>
    </StackPanel>
</Window>


Code behind,
public partial class Window1 : Window
{
    DispatcherTimer _timer;

    public Window1()
    {
        InitializeComponent();

        _timer = new DispatcherTimer();
        _timer.Tick += new EventHandler(delegate(object s, EventArgs a)
        {
            status.Text = "Started: " + DateTime.Now;
            //MessageBox.Show("Dummy message"); //notify timer end
            //this.Close(); //close application
        });
    }

    private void Start_Click(object sender, RoutedEventArgs e)
    {
        // Set the Interval
        _timer.Interval = TimeSpan.FromMilliseconds(Convert.ToDouble(time.Text));

        // Start the timer
        _timer.Start();

        status.Text = "Started";
    }

    private void Stop_Click(object sender, RoutedEventArgs e)
    {
        // Stop the timer
        _timer.Stop();

        status.Text = "Stopped";
    }
}


We have a local variable of type DispatcherTimer - _timer. We manipulate this variable to start and stop the timer. At start we initialize the variable with an Event delegate to fire whenever the Timer ticks.
 _timer.Tick += new EventHandler(delegate(object s, EventArgs a)
        {
            status.Text = "Started: " + DateTime.Now;
            //MessageBox.Show("Dummy message"); //notify timer end
            //this.Close(); //close application
        });


I have specifically left the commented lines to show the different possibilities that can be done in the Event delegate. Whenever the Timer ticks the event is fired and Status bar is updated with the most recent DateTime.

DispatcerTimer runs on the UI thread and hence does not need marshaling back and forth as we have to do in the normal cases of a Thread.

Validate Email ID


function IsEmailValid(string)
{
    if(!IsNull(string))
    {
     var regex = new RegExp('^[\\w-_%\.]*[\\w-_%\.]\@[\\w]\
.+[\\w]+[\\w]$');
        return regex.test(string);
    }
    
    return false;
}

function IsNull(val)
{
    return (val == null || val == '');
}

Date Comparer in Javascript

This code is used to comapre date and sort dates.


function DateComparer(firstValue, SecondValue)
{
    var sortFirstRow  = GetFormattedDateForSort(firstValue);
    var sortSecondRow = GetFormattedDateForSort(SecondValue);
    
    if(sortFirstRow == sortSecondRow) return 0;
    if(sortFirstRow >  sortSecondRow) return 1;
    if(sortFirstRow <  sortSecondRow) return -1;
}
function GetFormattedDateForSort(value)
{
   var retValue = "";
   if(value != "")
   {
        var month   = value.split('/')[0];
        var day     = value.split('/')[1];
        var year    = value.split('/')[2];
        
        if(month != undefined)
        {
            if(month.length == 1 && month < 10)
            {
                month = '0' + month;
            }
        }
        if(day != undefined)
        {
            if(day.length == 1 && day < 10)
            {
                day = '0' + day;
            }
        }
        
        retValue = year + month + day ;
    }
    return retValue;
}

Basics of WPF

WPF should not be used just to be able to have stylish looking UI with zoomable multi-state 3D buttons. WPF solves one of the biggest problems with user experience - data visualization. How can an application present complex data to the user that provides a highly flexible and customizable way for the user to find the right item doing very little work (or clicks) or minimal guidance on navigation.

Some of the good examples can be seen from the following link:

http://channel9.msdn.com/Showpost.aspx?postid=109413
http://channel9.msdn.com/Showpost.aspx?postid=116327

WPF is a developer’s paradise. The platform has many features which make *programming* more enjoyable and flexible.

- The databinding in WPF is far more powerful and comprehensive than in WinForms. This reduces the amount of code you need to write, and allows you to easily bind to pretty much anything.
- Routed events change the way you work with events. Now that events route down and up the element tree, there are many more ways to design code which deals with events for many controls, or controls which are loaded dynamically.
- Attached properties let you set a property on any object, even though the object does not expose that property. The possibilities are endless!
- Triggers are an extremely useful way to express conditional logic in markup. Very convenient.
- WPF is common technology which can be used for both Web and Windows .In WPF, you can create layout (User Interface) which can be used both in Window and Web application. (i.e. Before WPF, you will have to create separate layout for windows and web.)
- There is a nice feature of WPF is XPS (XML Paper specification) which means document looks same on screen and on a printer.
- One nice feature of WPF is that there is no need to write code for GDI+ and Direct 3D objects because it has been handled by WPF.
- WCF supports internationalization.
The new features of WPF can be used in this application are as follows:
- Freezable Objects:
Freezable objects provide special features that can help improve application performance. Examples of freezable objects include brushes, pens, transformations, geometries, and animations.

http://www.codeproject.com/KB/WPF/GridLengthAnimation.aspx
http://msdn2.microsoft.com/en-us/library/ms750509.aspx

Visual tree and/or Logical tree:


XAML is natural for representing a user interface because of its hierarchical nature. In WPF, user interfaces are constructed from a tree of objects known as a logical tree.

http://msdn2.microsoft.com/en-us/library/ms753391.aspx

http://msdn2.microsoft.com/en-us/library/ms742244.aspx

http://www.codeproject.com/KB/WPF/WpfElementTrees.aspx

http://blogs.interknowlogy.com/johnbowen/archive/2007/04/01/12495.aspx

Content Model :


In WPF, different classes of elements are categorized based on the type and number of their logical children. These logical children are also referred as the "content" of the control. WPF defines several different "content models" for various different classes of elements.
The controls that can contain a single item (single logical child of type Object) are called "content controls". These controls derive from the ContentControl base class. Controls that can contain a collection of items (many logical children of type Object) are called "items controls". These controls derive from the ItemsControl base class.
There are different kinds of content models available in WPF like Controls content model, Decoder content model, Panel content model, TextBox and TextBlock content model.

http://msdn2.microsoft.com/en-us/library/ms751553.aspx

http://drwpf.com/blog/Home/tabid/36/EntryID/24/Default.aspx

Use of Data Templates:


Data templates are a natural extension of styling controls and elements provided in Windows Presentation Foundation. Just as we can apply a visual Style to a user interface (UI) element, we can apply a DataTemplate that can determine both visual aspects of how the data is presented and how data binding accesses the presented data.

By applying different data templates to the same data, one can flexibly change the visual appearance of the data in the application. Data templates can be applied to both Windows Presentation Foundation content controls (for example: Button and Hyperlink) and items controls (for example: ListBox, ComboBox, and Menu). These controls have built-in support for applying such data templates.

http://msdn2.microsoft.com/en-us/library/ms742521.aspx

http://www.longhorncorner.com/UploadFile/cook451/DataBindingXAML12102005134820PM/DataBindingXAML.aspx?ArticleID=a015a832-cbba-4e35-b287-3372a53e548e

http://www.beacosta.com/blog/?p=40

Drag and Drop:


Drag-and-drop commonly refers to a method of user interface (UI) interaction that involves using a mouse (or some other pointing device) to select one or more objects, dragging these objects over some desired drop target in the UI, and dropping them.

http://msdn2.microsoft.com/en-us/library/ms746687.aspx

http://thewpfblog.com/?p=59