Wednesday, February 29, 2012

Windows 8 Customer Preview Installation stpes

Here are the steps to install Windows 8 Customer preview using ISO file
1) Download and install "Oracle VM Virtual Box Manager" from http://www.oracle.com/technetwork/server-storage/virtualbox/downloads/index.html.

2) Download a ISO version of windows 8 from http://windows.microsoft.com/en-US/windows-8/iso .

3) Once you have Virtual Box installed, follow steps to create a virtual machine, and while creating virtual machine, select your OS as Windows 8 , specify RAM size and create a virtual hard drive for the new machine.

4) Now using Daemon tool mount your ISO file which you downloaded in step 2 to a drive lets say "E:".

4) Once you have mounted your ISO file now return to Virtual Box, and select the virtual machine you had created in step 3 and power-on that machine. While you are putting on that machine select E: drive as your boot drive and follow steps.

5) You will see your windows installation starts, enter product key which is "DNJXJ-7XBW8-2378T-X22TX-BKG7J" and follow steps, and you will have Windows 8 installed.


6) Enjoy Windows 8!!!

Saturday, February 25, 2012

WPF : Validation Summary Control

In this post I am going to build a validation summary control like ASP.net and Silverlight.
We will build that in 2 steps. In 1st step we will build a simple control which will have an Itemscontrol and it will list all errors sequentally, and In second step we will write an attached property which will attach any control that wants its error tobe shown in validation summary control.
So lets start with first steps, here we are going to build an usercontrol and will name it as ValidationSummary.
This  control in its XAML will have an ItemsControl which will have its Items property bounded to a list of error message. This control will maintain a Dictionary of controls which is going to be subscribe and wants their messages to be shown in ValidationSummaryControl.  For each of control subscribed ValidationSummayControl will listen for ValidationError and for every error in Validation.GetErrors method it will list errors.
Here is the code for ValidationSummary's XAML view.

<UserControl x:Class="Controls.ValidationSummary"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             x:Name="validationSummary"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <DataTemplate x:Key="ErrorViewerItemTemplate" DataType="string" >
            <StackPanel Orientation="Horizontal">
                <Ellipse Fill="Red" Width="5" Height="5" VerticalAlignment="Center"
             HorizontalAlignment="Center" Margin="5,0,0,0" />
                <TextBlock Text="{Binding}" FontSize="11" FontStyle="Italic"
            Foreground="red" Padding="2" Margin="5,0,0,0"
             HorizontalAlignment="Left" VerticalAlignment="Center" />
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
    <Grid>
        <ItemsControl x:Name="itemsControl" 
        ItemTemplate="{StaticResource ErrorViewerItemTemplate}"  />
    </Grid>
</UserControl>

Here is the code for ValidationSummary.cs file.

 
namespace Controls
{
    /// <summary>
    /// Interaction logic for ValidationSummary.xaml
    /// </summary>
    [ExcludeFromCodeCoverage]
    public partial class ValidationSummary : UserControlIErrorViewer
    {
        #region Private variables
 
        private readonly List<DependencyObject> _elements = new List<DependencyObject>();
 
        private readonly Dictionary<FrameworkElementstring> _errorMessages =
            new Dictionary<FrameworkElementstring>();
 
        #endregion
 
        #region Constructor
 
        public ValidationSummary()
        {
            InitializeComponent();
        }
 
        #endregion
 
        #region Methods
 
        public void SetElement(DependencyObject element)
        {
            if (!_elements.Contains(element))
            {
                _elements.Add(element);
                Validation.AddErrorHandler(element, Element_ValidationError);
            }
        }
 
        private void Element_ValidationError(object sender, ValidationErrorEventArgs e)
        {
            GetErrorsRecursive(sender as FrameworkElement, _errorMessages);
        }
 
        private void GetErrorsRecursive(FrameworkElement elem, Dictionary<FrameworkElementstring> errors)
        {
            errors.Remove(elem);
 
            if (Validation.GetHasError(elem))
                foreach (ValidationError error in Validation.GetErrors(elem))
                {
                    errors.Add(elem, error.ErrorContent.ToString());
                    break;
                }
 
            foreach (object child in LogicalTreeHelper.GetChildren(elem))
                if (child is FrameworkElement)
                    GetErrorsRecursive(child as FrameworkElement, errors);
 
            itemsControl.ItemsSource = null;
            itemsControl.ItemsSource = _errorMessages.Values;
        }
 
        #endregion
    }
}

Now let's start with step 2 where we will write an attached property that will attach an element which wants to show error message in above ValidationSummary control.
Here is the code for ValidationSummaryValidator
using System;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using Prudential.SCT.BPC.FrontEnd.Core.Interfaces.Infrastructure;
 
namespace Prudential.SCT.BPC.FrontEnd.Core.Common
{
    /// <summary>
    /// This class is used to attach ValidationSummary control with controls on View.
    /// </summary>
    [ExcludeFromCodeCoverage]
    public static class ValidationSummaryValidator
    {
        #region "AdornerSite"
 
        /// <summary>
        /// Attached Property : AdornerSite
        /// It will let framework elements who want to be a part of ValidationSummary control, subscribe themselves.
        /// </summary>
        public static DependencyProperty AdornerSiteProperty = DependencyProperty.RegisterAttached("AdornerSite",
                                                                                                   typeof (
                                                                                                       DependencyObject),
                                                                                                   typeof (
                                                                                                       ValidationSummaryValidator
                                                                                                       ),
                                                                                                   new PropertyMetadata(
                                                                                                       null,
                                                                                                       OnAdornerSiteChanged));
 
 
        /// <summary>
        /// Gets Validation Subscribing elements
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        [AttachedPropertyBrowsableForType(typeof (DependencyObject))]
        public static DependencyObject GetAdornerSite(DependencyObject element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            return (element.GetValue(AdornerSiteProperty) as DependencyObject);
        }
 
        /// <summary>
        /// Adds elements that want to be a part of Validation summary control
        /// </summary>
        /// <param name="element"></param>
        /// <param name="value"></param>
        public static void SetAdornerSite(DependencyObject element, DependencyObject value)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            element.SetValue(AdornerSiteProperty, value);
        }
 
        /// <summary>
        /// CallBack for Adorner site whenever it it set.
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void OnAdornerSiteChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var errorViewer = e.NewValue as IErrorViewer;
            if (errorViewer != null)
            {
                errorViewer.SetElement(d);
            }
        }
 
        #endregion
    }
}

Now lets see how you will bind a text box control with ValidationSummary control. 
First you will add an instance of ValidationSummaryControl in your XAM view as show below

<Controls:ValidationSummary Grid.Row="7" Visibility="Hidden" x:Name="validationSummary" />

Then you will pick up the control which you want to attach in your view, here we are going to pick up a textbox 

<TextBox common:ValidationSummaryValidator.AdornerSite="validationSummary"
  Text="{Binding CustomText,ValidatesOnDataErrors=true,NotifyOnValidationError=True
}"  />

Thursday, February 23, 2012

WPF : An introduction to EventManger class

I am going to introduce EventManager class, Lets look at definition available for EventManager class in VS

#region Assembly PresentationCore.dll, v4.0.30319
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\PresentationCore.dll
#endregion
using MS.Internal.PresentationCore;
using System;
using System.Runtime;
 
namespace System.Windows
{
    public static class EventManager
    {
        public static RoutedEvent[] GetRoutedEvents();
        public static RoutedEvent[] GetRoutedEventsForOwner(Type ownerType);
        [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")]
        public static void RegisterClassHandler(Type classType, RoutedEvent routedEvent, Delegate handler);
        public static void RegisterClassHandler(Type classType, RoutedEvent routedEvent, Delegate handler, bool handledEventsToo);
        public static RoutedEvent RegisterRoutedEvent(string name, RoutingStrategy routingStrategy, Type handlerType, Type ownerType);
    }
}


So, as we can see that 
  • Its defined in PresentationCore dll.
  • It exposes a GetRoutedEvents function which can be used to find all RoutedEvent which have been defined in current application. A simple call to GetRoutedEvents in a blank WPF application returns 135 events as can be seen below.
  • It exposes GetRoutedEventsForOwner method which takes a particular class type or control and returns all Routed events defined in that class/control.
  • It exposes RegisterClassHandler method which is used to declare a class level routed event handle. Class level routed event handler are called first before raising any other handler for a particular routed event.
  • It exposes RegisterRoutedEvent method which is used to declare routed event.

WPF : Dependency Property Value Precedence

As we know that Dependency properties support value inheritance and can be set from different places which includes Animation, Direct code, based on TemplatedParent, Triggers, There is a precedence involved here which decides what would be value for a particular dependency property if its set from multiple sources.
There precedence is listed below

1. Set by coercion by the property system. This is specified through Metadata while defining a Dependency Property.
2. Set by active animations or held animations, You define animations using storyboard and change value for a particular property using Storyboard.TargetProperty.
3. Set locally by code, by direct setting in XAML, or through data binding, you can set the value by calling DependencyProperty.SetValue or using Binding.
4. Set by TemplatedParent. Within this category is a sub-order of precedence, again listed
in descending order:
a. Set by triggers from the templated parent using, we have 2 types of triggers which are Property Trigeer or Data Trigger and they can set value for properties using Setters in Trigger block.
b. Set by the templated parent through property sets
5. Implicit style; this applies only to the Style property.
6. Set by Style triggers.
7. Set by Template triggers.
8. Set by Style setters.
9. Set by the default Style. There is a sub-order within this category, again listed in descending
order:
a. Set by triggers in the default style
b. Set by setters in the default style
10. Set by inheritance.
11. Set by metadata.

  

Wednesday, February 22, 2012

WPF : Enhancing GridSplitter control to show Left, Right , Up and Down button like lotus notes

In this article , I am going to enhance Grid splitter in WPF to show Up/Down or Left/Right button like Lotus notes application.

Step 1) We start with creating a custom control which is derived from Existing GridSplitter control and change its control template to have four buttons as needed in Vertical Template and Horizontal Template.

using System.Diagnostics.CodeAnalysis;
using System.Windows;
using System.Windows.Controls;

namespace Controls
{
    [TemplatePart(Name = VerticalLeftButtonElement, Type = typeof (Button))]
    [TemplatePart(Name = VerticalRightButtonElement, Type = typeof (Button))]
    [TemplatePart(Name = HorizontalUpButtonElement, Type = typeof (Button))]
    [TemplatePart(Name = HorizontalDownButtonElement, Type = typeof (Button))]
    public class CustomGridSplitter : GridSplitter
    {
        #region Constants

        const string VerticalLeftButtonElement = "VerticalLeftButton";
        const string VerticalRightButtonElement = "VerticalRightButton";

        const string HorizontalUpButtonElement = "HorizontalUpButton";
        const string HorizontalDownButtonElement = "HorizontalDownButton";

        const string LowerButtonGridElement = "LowerButtonGrid";
        const string UpperButtonGridElement = "UpperButtonGrid";

        const string MiddleVerticalButtonElement = "MiddleVerticalButton";
        #endregion

        #region Private Variables

        protected Button HorizontalDownButton;
        protected Button HorizontalUpButton;
        protected Button VerticalLeftButton;
        protected Button VerticalRightButton;
        protected Button MiddleVerticalButton;
        #endregion

        #region Methods

        /// <summary>
        /// It is called while applying templates.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();

            VerticalLeftButton = GetTemplateChild(VerticalLeftButtonElement) as Button;
            if (VerticalLeftButton != null)
            {
                VerticalLeftButton.Click += OnLeftButtonClickEvent;
            }

            VerticalRightButton = GetTemplateChild(VerticalRightButtonElement) as Button;
            if (VerticalRightButton != null)
            {
                VerticalRightButton.Click += OnRightButtonClickEvent;
            }

            HorizontalUpButton = GetTemplateChild(HorizontalUpButtonElement) as Button;
            if (HorizontalUpButton != null)
            {
                HorizontalUpButton.Click += OnUpButtonClickEvent;
            }

            HorizontalDownButton = GetTemplateChild(HorizontalDownButtonElement) as Button;
            if (HorizontalDownButton != null)
            {
                HorizontalDownButton.Click += OnDownButtonClickEvent;
            }

            MiddleVerticalButton = GetTemplateChild(MiddleVerticalButtonElement) as Button;
            if (MiddleVerticalButton != null)
            {
                MiddleVerticalButton.Click += OnMiddleButtonClick;
            }
        }

     

        /// <summary>
        /// Its called to set width and hight of buttons.
        /// </summary>
        /// <param name="availableSize"></param>
        /// <returns></returns>
        protected override Size MeasureOverride(Size availableSize)
        {
            VerticalRightButton.Width = 8;
            VerticalLeftButton.Width = 8;
            HorizontalUpButton.Height = 8;
            HorizontalDownButton.Height = 8;

            return base.MeasureOverride(availableSize);
        }

        /// <summary>
        /// it invokes left click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLeftButtonClickEvent(object sender, RoutedEventArgs e)
        {
            if (LeftButtonClickEvent != null) LeftButtonClickEvent(sender);
        }

        /// <summary>
        /// it invokes right click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRightButtonClickEvent(object sender, RoutedEventArgs e)
        {
            if (RightButtonClickEvent != null) RightButtonClickEvent(sender);
        }

        /// <summary>
        /// it invokes up click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnUpButtonClickEvent(object sender, RoutedEventArgs e)
        {
            if (UpButtonClickEvent != null) UpButtonClickEvent(sender);
        }

        /// <summary>
        /// it invokes middle button click event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnMiddleButtonClick(object sender, RoutedEventArgs e)
        {
            if (MiddleButtonClickEvent != null) MiddleButtonClickEvent(sender);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnDownButtonClickEvent(object sender, RoutedEventArgs e)
        {
            if (DownButtonClickEvent != null) DownButtonClickEvent(sender);
        }



        #endregion

        #region Properties

        #region Delegates

        public delegate void ButtonClickEventHandler(object sender);

        #endregion

        #region Events
     
        public event ButtonClickEventHandler LeftButtonClickEvent;
        public event ButtonClickEventHandler RightButtonClickEvent;
        public event ButtonClickEventHandler UpButtonClickEvent;
        public event ButtonClickEventHandler DownButtonClickEvent;
        public event ButtonClickEventHandler MiddleButtonClickEvent;
        #endregion

        #region UseHorizontally

        /// <summary>
        /// UseHorizontally Dependency Property
        /// </summary>
        public static readonly DependencyProperty UseHorizontallyProperty =
            DependencyProperty.Register("UseHorizontally", typeof (bool), typeof (ExtendedGridSplitter),
                                        new FrameworkPropertyMetadata(false));

        /// <summary>
        /// Gets or sets the UseHorizontally property. This dependency property
        /// indicates ....
        /// </summary>
        public bool UseHorizontally
        {
            get { return (bool) GetValue(UseHorizontallyProperty); }
            set { SetValue(UseHorizontallyProperty, value); }
        }

        #endregion

        #endregion

        #region Static Constructor

        /// <summary>
        /// its a default static contructor.
        /// </summary>
        static ExtendedGridSplitter()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof (ExtendedGridSplitter),
                                                     new FrameworkPropertyMetadata(typeof (ExtendedGridSplitter)));
        }

        #endregion
    }
}

2) You define control template for this control as 
 <Style TargetType="{x:Type controls:CustomGridSplitter}">
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="IsTabStop" Value="true"/>
        <Setter Property="Width" Value="15"/>
        <Setter Property="PreviewStyle" Value="{StaticResource GridSplitterPreviewStyle}"/>
        <Setter Property="HorizontalAlignment" Value="Right"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="controls:CustomGridSplitter">
                    <Grid x:Name="Root" IsHitTestVisible="{TemplateBinding IsEnabled}">

                        <!-- VSM -->
                        <VisualStateManager.VisualStateGroups>
                            <VisualStateGroup x:Name="CommonStates">
                                <VisualState x:Name="Normal" />
                                <VisualState x:Name="MouseOver" />
                                <VisualState x:Name="Disabled">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="Root" Storyboard.TargetProperty="Opacity" To="0.5" Duration="0" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                            <VisualStateGroup x:Name="FocusStates">
                                <VisualStateGroup.Transitions>
                                    <VisualTransition GeneratedDuration="0" />
                                </VisualStateGroup.Transitions>
                                <VisualState x:Name="Unfocused" />
                                <VisualState x:Name="Focused">
                                    <Storyboard>
                                        <DoubleAnimation Storyboard.TargetName="FocusVisual" Storyboard.TargetProperty="Opacity" To="1" Duration="0" />
                                    </Storyboard>
                                </VisualState>
                            </VisualStateGroup>
                        </VisualStateManager.VisualStateGroups>

                        <!-- Background -->
                        <Border CornerRadius="1"  BorderBrush="#8CACDB" BorderThickness="1,1,2,1"  >
                            <Border CornerRadius="1" BorderThickness="0,0,1,0" BorderBrush="DarkBlue" />
                        </Border>
                        
                        
                        <!-- Horizontal Template -->
                        <Grid x:Name="HorizontalTemplate" 
                              Visibility="{Binding UseHorizontally, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type controls:ExtendedGridSplitter}},Converter={StaticResource BoolToVisibilityConverter}}"  
                              HorizontalAlignment="Center" VerticalAlignment="Center">
                            <StackPanel Orientation="Horizontal"  >
                            <Button Style="{StaticResource SplitterButtonStyle}" Content="5" x:Name="HorizontalUpButton" 
                                Width="Auto"/>
                            <Button Style="{StaticResource SplitterButtonStyle}" Content="6" x:Name="HorizontalDownButton" 
                                Width="Auto"/>
                            </StackPanel>    
                        </Grid>

                        <!-- Vertical Template -->
                        <Grid x:Name="VerticalTemplate" HorizontalAlignment="Center" 
                              Visibility="{Binding UseHorizontally, 
                                RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type controls:ExtendedGridSplitter}},
                                Converter={StaticResource NotBoolToVisibilityConverter}}"  
                              VerticalAlignment="Stretch"  >
                            <Grid.RowDefinitions>
                                <RowDefinition Height="0.3*"/>
                                <RowDefinition Height="0.3*"/>
                                <RowDefinition Height="0.3*"/>
                            </Grid.RowDefinitions>

                            <Button Grid.Row="0" ToolTip="Expand Right"  Style="{StaticResource SplitterButtonStyle}"  VerticalContentAlignment="Bottom"  Content="3"  x:Name="VerticalLeftButton" 
                            Height="Auto"/>

                            <Button Grid.Row="2" ToolTip="Expand Left" Style="{StaticResource SplitterButtonStyle}" VerticalContentAlignment="Top" Content="4"  x:Name="VerticalRightButton"
                            Height="Auto"/>

                            <Button Grid.Row="1" ToolTip="Restore Center" Style="{StaticResource SplitterButtonStyle}" VerticalContentAlignment="Center" x:Name="MiddleVerticalButton"
                            Height="Auto"/>
                            
                        </Grid>

                        <!-- Focus Visual -->
                        <Rectangle x:Name="FocusVisual" Stroke="#FF45D6FA" StrokeThickness="1" Opacity="0" IsHitTestVisible="false" />
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>



Step 3) You add this Control in your window as shown below

 <Grid Grid.Row="1" x:Name="ContainerGrid"  >
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="0.5*" />
                <ColumnDefinition Width="Auto" />
                <ColumnDefinition Width="0.5*" />
            </Grid.ColumnDefinitions>
            <TabControl Grid.Column="0" />
            <controls:ExtendedGridSplitter Grid.Column="1"                                           MouseDoubleClick="GridSplitter_MouseDoubleClick"                                            x:Name="GridSplitter" Margin="0,5"                                            ShowsPreview="True" Background="Transparent" DragCompleted="GridSplitter_DragCompleted"                                             Width="10" LeftButtonClickEvent="GridSplitter_LeftButtonClickEvent" MiddleButtonClickEvent="GridSplitter_MiddleButtonClickEvent"                                         RightButtonClickEvent="GridSplitter_RightButtonClickEvent"                                            HorizontalAlignment="Center" VerticalAlignment="Stretch"  >                           </controls:ExtendedGridSplitter>
            <TabControl Grid.Column="2" Background="Transparent"Name="Right" />
        </Grid>



Step 4) Put code for GridSplitter_LeftButtonClickEvent and GridSplitter_RightButtonClickEvent to change width of left and right portion as indicated below.

        private void GridSplitter_LeftButtonClickEvent(object sender)
        {
            SetLeftScreenWidth();
        }
        private void GridSplitter_RightButtonClickEvent(object sender)
        {
            SetRightScreenWidth();
        }

In  SetLeftScreenWidth method you will increase size for left side and in 
SetRightScreenWidth method you will increase size for right section.

WCF : Creating a binding(basichttp/nettcp) based on configuration

I am going to write a method here which will based on configuration return a BasicHttpBinding or NetTcpBinding. You will need to do something like this during development / qa phase when you wants to change you service infrastructure based on available resources.

In this piece of code, I am also  going to set ReaderQuotas to read max possible string, as in 1 of service we were returning a whole chunk of data.


public Binding GetBinding()
        {
            if (ConfigurationManager.Appsettig["ServiceKeyProtocol"].Equals("net.tcp"))
            {
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.None);
                binding.MaxReceivedMessageSize = Int32.MaxValue;
                binding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
                binding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
                binding.ReaderQuotas.MaxDepth = Int32.MaxValue;
                binding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
                binding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
                return binding;
            }
            else 
            {
                BasicHttpBinding httpbinding = new BasicHttpBinding(BasicHttpSecurityMode.None);
                httpbinding.MaxReceivedMessageSize = Int32.MaxValue;
                httpbinding.ReaderQuotas.MaxArrayLength = Int32.MaxValue;
                httpbinding.ReaderQuotas.MaxBytesPerRead = Int32.MaxValue;
                httpbinding.ReaderQuotas.MaxDepth = Int32.MaxValue;
                httpbinding.ReaderQuotas.MaxNameTableCharCount = Int32.MaxValue;
                httpbinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;
 
                return httpbinding;
            }
        }