Saturday, November 5, 2011

WPF is still alive...............

(Until Windows 8 gets more than 50% of windows market share J
After absorbing the shock waves from Microsoft Build 2011 , I was wondering what will happen to the future of WPF/Silverlight but a simple comparison of WPF 4.5 feature set shows that it contains more real features than WPF 4.0 release (WPF 4.0 contains only minor improvement over 3.5). Let’s look into some of my favorite enhancements in  WPF 4.5.
1.      Improved performance when displaying large sets of grouped data :
The much awaited feature for all WPF developer is here. It consists of 2 parts. First the virtualization in ItemControl (As per build slides now ItemControl can render 200000 items in 2.3 ms).  VirtualizingStackPanel now can render the item based on items/ Pixel while scrolling. You can specify whether a VirtualizingPanel, such as the VirtualizingStackPanel, displays partial items by using the ScrollUnit attached property. If ScrollUnit is set to Item, the VirtualizingPanel will only display items that are completely visible. If ScrollUnit is set to Pixel, the VirtualizingPanel can display partially visible items.
Also you can specify the size of the cache before and after the viewport when the VirtualizingPanel is virtualizing by using the CacheLength attached property. The cache is the amount of space above or below the viewport in which items are not virtualized. Using a cache to avoid generating UI elements as they’re scrolled into view can improve performance. The cache is populated at a lower priority so that the application does not become unresponsive during the operation.
2.      Accessing collections on non-UI Threads:
No more runtime exception while accessing UI controls from background thread.
3.      Asynchronously validating data:
As name indicate no more unresponsive UI for complex data driven validations. The INotifyDataErrorInfo interface enables data entity classes to implement custom validation rules and expose validation results asynchronously. This interface also supports custom error objects, multiple errors per property, cross-property errors, and entity-level errors. For more information, see INotifyDataErrorInfo.
4.      Delay Update in data binding:
If you use a data binding to update a data source, you can use the Delay property to specify an amount of time to pass after the property changes on the target before the source updates.
5.      Asynchronously validating data:
No more unresponsive UI on complex domain driven validation. The INotifyDataErrorInfo interface enables data entity classes to implement custom validation rules and expose validation results asynchronously. This interface also supports custom error objects, multiple errors per property, cross-property errors, and entity-level errors. For more information, see INotifyDataErrorInfo.
6.      Repositioning data as the data's values change (Live shaping) :
A collection of data can be grouped, sorted, or filtered. WPF 4.5 enables the data to be rearranged when the data is modified. For example, suppose that an application uses a DataGrid to list stocks in a stock market and the stocks are sorted by stock value. If live sorting is enabled on the stocks' CollectionView, a stock's position in the DataGrid moves when the value of the stock becomes greater or less than another stock's value. For more information, see the ICollectionViewLiveShaping interface.
7.      Integrating WPF with win32 Graphical User Interfaces :
No more air gap issue with win32 control hosted in WPF J.

And much more …………………………………
for more update on WPF 4.5 features.

Sunday, September 18, 2011

Some big news coming out of Microsoft's Build 2011

 Yesterday I was anxiously waiting for the news from Microsoft Build 2011. Everyone from tech community is expecting some big announcement from Microsoft.
And Microsoft stood up to the expectation & announced some big ticket changes in technology too (good or bad is up to you J).

1.      Windows 8 developer preview release:
The first developer preview version of windows 8 is out & you can try out at  http://msdn.microsoft.com/en-us/windows/apps/br229516
Some highlights of Windows 8 :
·         First Microsoft’s OS to exclusively designed for tablets.
·         First Microsoft’s OS to run on ARM architecture (good bye to Intel).
·         Heavily influenced by Metro UI of Windows 7 mobile (In opinion metro UI looks crap ).
·         Supports HTML5 / CSS based application.(Microsoft is putting XAML and HTML/CSS on an equal footing in that regard. So speculation is  WPF/Silverlight might not be the preferred UI language for Windows platform)
·         Multiserver management. (Server version only)
·         Friction-free server deployment( Windows Server 8 inherits Windows Server 2008's wizards for installing roles and features,
but combines them in what Microsoft calls "scenario-based deployment." Server version only)
·         IP address management (Windows Server 8 introduces a full-featured IP address manager that combines network discovery, static and dynamic address allocation,
DNS and DHCP monitoring, and network auditing capabilities all in one place. Server version only)
·         Dynamic Access Control (Server version only)
Today's folder-centric model for access control makes it all too easy for permissions to get garbled  and auditing is a horror.
Dynamic Access Control doesn't replace your current file and folder permissions, but allows you to layer global policies and claims-based access controls on top of them (just like circles in Google +).

2.      Visual Studio 11 developers preview: (Available in MSDN downloads )
Visual Studio 11 provides an integrated development experience that spans the entire lifecycle of software creation from architecture to code creation, testing and beyond.
This release adds support for Windows 8 and HTML 5, enabling you to target platforms across devices, services and the cloud.
Key Features :
·         Develop Metro style Apps for Windows 8. (Template support for Metro style app in various languages like C# , VB, C++).
·         Open Expression Blend support from VS 11.
·         Enhancements for Game Development (Visual Studio 11 provides access to a number of resource editing, visual design, and visual debugging tools for writing 2D / 3D games and Metro style applications.)
·         Code Clone Analysis (Much awaited).
The Code-Clone Analysis tool in Visual Studio 11 examines your solution looking for logic that is duplicated, enabling you to factor
this code out into one or more common methods. The tool does this very intelligently; it does not just search for identical blocks of
code, rather it searches for semantically similar constructs using heuristics developed by Microsoft Research.
·         Code Review Workflow with Team Explorer:
Visual Studio 11 Preview works hand in hand with Team Foundation Server 11 to provide best in class application lifecycle management.
Visual Studio 11 facilities collaboration is by enabling developers to request and perform code reviews through using Team Explorer.
·         Exploratory Testing and Enhanced Unit Testing:
The Exploratory Testing feature is an adaptive tool for agile testing that enables you to test without performing formal test planning. You can now directly
start testing the product without spending time writing test cases or composing test suites. When you start a new testing session, the tool generates a
full log of your interaction with the application under test. You can annotate your session with notes, and you can capture the screen at any point and add the resulting screen shot to your notes.
3.      .Net 4.5: (Available in MSDN downloads)
Following are some features:
·         .NET for Metro style apps. (Obvious)
·         Async support in c#:
The feature introduces two new keywords, async and await. The async modifier specifies that a method is
an async method. When called, an async method returns a Task or Task(Of TResult), which represents the ongoing work of the method.
·         The Managed Extensibility Framework (MEF) provides the following new features:
o   Support for generic types.
o   Convention-based programming model that enables you to create parts based on naming conventions rather than attributes.
o   Multiple scopes.
·         A bunch of new features for ASP.NET 4. Like new HTML5 form types, unobtrusive JavaScript in client-side validation scripts, encoding routines from the AntiXSS library (previously an external library) to protect from cross-site scripting attacks etc.
·         In the .NET Framework 4.5 Developer Preview, Windows Presentation Foundation (WPF) contains changes and improvements in the following areas:
o   The new Ribbon control, which enables you to implement a ribbon user interface that hosts a Quick Access Toolbar, Application Menu, and tabs.
o   The new INotifyDataErrorInfo interface, which supports synchronous and asynchronous data validation.
o   New features for the VirtualizingPanel and Dispatcher classes.
o   Improved performance when displaying large sets of grouped data, and by accessing collections on non-UI threads.
o   Data binding to static properties, data binding to custom types that implement the ICustomTypeProvider interface, and retrieval of data binding information from a binding expression.
o   Repositioning of data as the values change (live shaping).
o   Better integration between WPF and Win32 user interface components.
o   Ability to check whether the data context for an item container is disconnected.
o   Ability to set the amount of time that should elapse between property changes and data source updates.
o   Improved support for implementing weak event patterns. Also, events can now accept markup extensions.
·         From WCF:
o   Simplification of generated configuration files.
o   Support for contract-first development.
o   Ability to configure ASP.NET compatibility mode more easily.
o   Changes in default transport property values to reduce the likelihood that you will have to set them.
o   Updates to the XmlDictionaryReaderQuotas class to reduce the likelihood that you will have to manually configure quotas for XML dictionary readers.
o   Validation of WCF configuration files by Visual Studio as part of the build process, so you can detect configuration errors before you run your application.
o   New asynchronous streaming support.
o   New HTTPS protocol mapping to make it easier to expose an endpoint over HTTPS with Internet Information Services (IIS).
o   Ability to generate metadata in a single WSDL document by appending ?singleWSDL to the service URL.
o   Websockets support to enable true bidirectional communication over ports 80 and 443 with performance characteristics similar to the TCP transport.
o   Support for configuring services in code.
o   XML Editor tooltips.
o   ChannelFactory caching support.
o   Binary encoder compression support.

For more details please visit

Saturday, September 10, 2011

TextBlock Vs. Label (The Ultimate battle for UI Supremacy)


In WPF both Textblock and Label are used to show a small amount of text means visually both snippets produce the same UI.
But if you always has this confusion which one to use (Label or TextBlock) when showing a readonly data in GUI? Then just try to show “Label_Vs_TextBlock” in UI you will get your answer.
Label will show it as “LabelVs_TextBlock” (Label.Content = "Label_Vs_TextBlock").
TextBlock will show it as “Label_Vs_TextBlock”  (TextBlock.Text= "Label_Vs_TextBlock").
As you can see Label is taking the first Underscore as AccessKey & removing it. While TextBlock is showing it perfectly.
So what does this mean TextBlock has won the ultimate war for showing readOnly text on your UI.
Then you are wrong, think again ………………

There is a big difference between the two:
TEXTBLOCK: TextBlock lives in the System.Windows.Controls namespace, it is not a control. It derives directly from FrameworkElement. TextBlocks are used in a lot of controls to display text.

LABEL:
Label, on the other hand, derives from ContentControl means that label can: be given a custom control template (viaTemplate property), Display data other than just a string (via Content property), Apply a DataTemplate to its content (via ContentTemplate property), and you can do whatever else a ContentControl can do that a FrameworkElement cannot. It supports access keys.


Label vs TextBlock (class hierarchy)

Still, If the above problem of accessKey is a nightmare to you help yourself & use the  below style
      <Style x:Key="{x:Type Label}" TargetType="Label"> 
        <Setter Property=
"Template"> 
          <Setter.Value> 
            <ControlTemplate TargetType=
"Label"> 
              <Border> 
                <ContentPresenter 
                  HorizontalAlignment=
"{TemplateBinding HorizontalContentAlignment}" 
                  VerticalAlignment=
"{TemplateBinding VerticalContentAlignment}" 
                  RecognizesAccessKey=
"False" /> 
              </Border> 
            </ControlTemplate> 
          </Setter.Value> 
        </Setter> 
     
</Style> 


CONCLUSION:
If you want to use styles in WPF correctly (and you need to modify the margin, etc), It is recommended to use a Label instead of a TextBlock. TextBlocks are used inside a lot of controls, and modifying the TextBlock style has a major impact on how most controls (such as a Button, ComboBox, GridView Columns, etc) behave.

So, if you want to display text as a control itself, always use Label. The benefits of showing
styles correctly (and have more control over styles and themes) are better than the fact that a TextBlock is lighter.  

Sunday, July 24, 2011

Extended WPF Toolkit Rocks

Recently while searching for wpf property grid I came across extended wpf toolkit by Brian Lagunas.
It not only contains an excellent wpf property grid but also a bunch of useful controls like
·         BusyIndicator
·         ButtonSpinner
·         Calculator
·         CalculatorUpDown
·         ChildWindow
·         ColorCanvas
·         ColorPicker  
·         DateTimePicker
·         DateTimeUpDown
·         DecimalUpDown  
·         DoubleUpDown  
·         IntegerUpDown  
·         Magnifier
·         MaskedTextBox
·         MessageBox
·         RichTextBox
·         RichTextBoxFormatBar
·         SplitButton  
·         TimePicker  
·         WatermarkTextBox
(What more u wants from god?J)
Though the documentation is self-explanatory I had made a small solution to demonstrate all the control in one window.

Tuesday, July 12, 2011

Understanding HierarchicalDataTemplate with TreeView

Right from the time I started making WPF UI HierarchicalDataTemplate are always mistery to me until I came across this article in Code Project

Though this article is excellent but it is focused on how to show checkbox with TreeView. In this blog I will explain the basic of the HierarchicalDataTemplate with the example shared in CodeProject article.
First thing you need to understand about HierarchicalDataTemplate (or HDT) is they are mean to show your hierarchical data, it can nested structures like
Class Foo
{
            String Name;
            List<Foo> Childs;
}
In above case your HDT should look like:

 <HierarchicalDataTemplate DataType="{x:Type base:Foo}" ItemsSource="{Binding Childs}">
                    <TextBlock Text="{Binding Name}"/>
 </HierarchicalDataTemplate>

As HDT is a data template you have to target a datatype in our case we have Foo class. Now ItemSource should be binded to the items which want to show. Please remember in this case as , all the Childs are again of type Foo so same HDT will be applied by the WPF parser to render it. Now as each Foo contains Name property you can bind it to any control defined in the template (in this case TextBlock).

You can show hierarchies of different classes using multiple classes using more than one HDT (do remember if your structure contains more list of more than one datatype you have to use more than one HDT). Like

Class Dummy
{
     List<string> names;
}

Class Foo
{
            String FooName;
            List< Dummy > Childs;
}
HDT will look like
 <HierarchicalDataTemplate DataType="{x:Type Foo}" ItemsSource="{Binding Childs}">
                    <TextBlock Text="{Binding FooName}"/>
                </HierarchicalDataTemplate>                
                <DataTemplate DataType="{x:Type Dummy}" >
                    <TextBlock Text="{Binding Name}"/>
                </DataTemplate>
 Note that here we had used another DataTemplate to further show each Dummy inside Foo.Childs.
You can also use more than one HDT when dealing with more complex data structure.
In the code (below link) there are 2 HDT used to show list of below class

public class Test
    {
        public string Name { get; set; }

        public List<FooViewModel> TestList { get; set; }
    }

Here FooViewModel is self-referential structure which contains both Parent & List of Childs of type FooViewModel.

<HierarchicalDataTemplate
                DataType="{x:Type local:FooViewModel}"
                    ItemsSource="{Binding Children}">
                    <StackPanel x:Name="SP" Background="{Binding BackgroundBrush}" Orientation="Horizontal">
                        <!-- These elements are bound to a FooViewModel object. -->
                        <CheckBox
                                    Focusable="False"
                                    IsChecked="{Binding IsChecked}"
                                    VerticalAlignment="Center"/>
                        <ContentPresenter
                                Content="{Binding Name}"
                                Margin="2,0"/>
                    </StackPanel>
                </HierarchicalDataTemplate>

                <HierarchicalDataTemplate
                         DataType="{x:Type local:Test}"       
                        ItemsSource="{Binding TestList}">
                    <StackPanel Orientation="Horizontal">
                        <!-- These elements are bound to a FooViewModel object. -->
                        <ContentPresenter
                            Content="{Binding Name}"
                            Margin="2,0"/>
                    </StackPanel>
                </HierarchicalDataTemplate>

Also I had modified the example to show how to databing to change background colors (you check the checkbox ).

In most of the real life project you have to handle different behaviors of TreeView from ViewModel , like if you use search in treeview you have to hide/show items or you have to change the view based itemSelected in the treeview.

Please find the code at

I thing this article will be helpful to you. Please provide any feedback or post any questions.

Sunday, July 10, 2011

Accordion Control for WPF

Few days ago I was looking for the accordion control available in WPF for once of my requirement.
I have to show a Hierarchical object to the user, but the content of the accordion should change based on whether there is multiple object in second level or not. So if there are multiple objects in 2nd level I have to show it in Tab control while if there is single object I have to show it in Listview.

After some googling I figure out there are 3 possible options for that.
  1. Use toolkit Accordion Control.
  2. Make your own accordion.
  3. Use ComponentOne Accordion. 


Option 1 (ToolKit):
Pros:
  1.  Easy to use .
  2. Licensing cost.
  3. Can be configured to cater your need.
  4. You can data bind to the control.
Cons:
  1. Still in preview phase.
  2.  Lots of small defects (Like being a ItemControl it don’t support ItemTemplate). 


Option 2 (Custom Control):
You can use wpf treeview to behave like an accordion control.
Pros:
  1. Highly customizable to your needs.
  2.  Highly reliable unlike toolkit where u can find defect now & then.
  3. You can databind it.
  4. No Licensing cost.

Cons:
  1. You need to make your hands dirty (But that’s the best thing a developer wantsJ).
  2.  It’s difficult to match the flexibility of toolkit accordion (you can change the orientation etc.).


Option 3 (ComponentOne Accordion)
ComponentOne provide a wpf accordion control. But this control is made on top on WPF toolkit accordion so behaves like same except CopmponentOne provides support & a nice look to toolkit accordion.

Pros:
  1. A production ready control with nice template.
  2. Can be used with wpf databinding.
  3. Support from ComponentOne Team.

Cons:
  1.  Licensing Cost.
  2. As build on top of toolkit accordion so expect the same non uniform behavior (as I mentioned above no ItemTemplate support even it is ItemControl). 
(In my view why someone wants to pay for this control if it is made on top of toolkit accordionJ)

Complete solution is at 

It contains detail solution for all the 3 options above mentioned.

Please feel free to ask any question via comments. If you like this posting please follow my blog.