Monday, 6 May 2013

Difference Between Dependency Property and Normal CLR Property in WPF

Difference Between Dependency Property and Normal CLR Property in WPF

The Normal CLR property and the dependency property look quite similar but the dependency property is more powerful and has more features. In WPF, dependency properties are used in Animation, Styles, Triggers, Templates, Validation, Data Binding, Layout etc.

Syntax Difference Between Dependency Property and Normal CLR Property

Syntax of Normal CLR Property

private int count;
public int Count
{
   get
   {
      return count;
   }
   set
   {
      count = value;
   }
}

Syntax of Dependency Property

public static DependencyProperty PageSizeProperty =
DependencyProperty.RegisterAttached("PageSize",
typeof(int), typeof(AttachedPropertySample),
             new PropertyMetadata(25,
             new PropertyChangedCallback(OnPageSizePropertyChanged)));

public int PageSize
{
    get
    {
        return (int) GetValue(PageSizeProperty);
    }
    set
    {
        SetValue(PageSizeProperty, value);
    }
}

In Built Change Notification

Dependency provides change notification when its value has been changed. You can specify Call Back while registering dependency property so user will get notification. This is mainly used in Data Binding. But CLR property has not any inbuilt change notification. So if you want your normal CLR proprety also notify changes, you have to implement INotifyPropertyChanged.

Value Resolution

CLR property reads value directly from private member while dependency property dynamically resolves value when you call GetValue() method of dependency property. The GetValue and SetValue methods are inherited from Dependency Object.

Value Inheritance

If you specify dependency property to top element it will be inherited to all child elements until child element specifically override the property. Dependency property value is resolved at runtime when you call GetValue() method. 

Suggestion: If your property will commonly be the source of a databinding (e.g. providing the Text for a TextBlock), I would recommend using a standard CLR property and having the containing class implement INotifyPropertyChanged.

Saturday, 4 May 2013

What is the difference between WPF and Silverlight?


What is the difference between WPF and Silverlight?

This article focuses on the difference between Silverlight and WPF technologies. Silverlight and Windows Presentation Foundation (WPF) both allow you to develop rich user experience applications based on XAML and the .NET Framework. For a period of time, Silverlight was called WPF/E, with the ‘E’ standing for ‘everywhere’. But there are some differences between the two technologies. Lets try to find out.

1. WPF is meant for developing rich applications for desktop platform while Silverlight is meant for developing rich browser based internet applications.

2. WPF is essentially the replacement to Winforms while Silverlight was introduced to compete with Adobe Flash.

3. Silverlight is a sub set of WPF in terms of features and functionality. WPF is based on the desktop CLR which is the full version of the CLR. Silverlight is based on a much smaller and more compact CLR which provides a great experience but does not have the full breadth of CLR features but only CoreCLR features.

4. You can use Silverlight applications regardless of the operating system you use, while WPF applications are restricted to later versions of the Windows operating system. For a WPF browser application, you need the .NET Framework to be installed in the client location while for Silverlight, you need only the plug-in. So in other words, WPF browser applications are OS dependent while Silverlight is not. A Silverlight plug-in can run in OSs other than Windows while we all know the .NET Framework only runs in Windows.

5. WPF supports 3 types of routed events (direct, bubbling, and tunneling). Silverlight supports direct and bubbling only.

Difference between Window and Page Controls in WPF?


Difference between Window and Page Controls in WPF?

In this article on "Difference between Window and Page Controls in WPF", I will try to explain the difference between window and page controls used in WPF. Both controls have different usage depending on different requirements of the application. Lets try to understand this difference.

1. Window Control (Window.xaml) are used for Windows Application while Page Control (Page.xaml) is used for making Browser Hosted Applications. Page can be implemented as root element in Xaml file and can contain single element similar to window.

<Page x:Class="WpfApplication1.Page1"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      Title="Page1">
      Welcome to WPF Page Navigation.
</Page>

Similar to normal xaml file you can specify page name StartupUrl inside App.xaml to open specific page.

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             StartupUri="Page1.xaml">
</Application>

2. Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer). 

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

Frame class provides inbuilt support NavigationFramework. Let’s have a look on below code.

<StackPanel>
    <TextBlock Margin="10">This is Main Window.</TextBlock>
    <Frame Margin="10"
        Source="Page1.xaml"
            JournalOwnership="OwnsJournal"></Frame>
</StackPanel>

Thursday, 2 May 2013

When and Why to Use UNITY Framework in .NET? Inversion of Control (IOC) and Dependency Injection(DI)

When and Why to Use UNITY Framework in .NET? Inversion of Control (IOC) and Dependency Injection(DI)

UNITY Framework is a framework of Microsoft to achieve Inversion of Control / Dependency Injection Design Pattern. IOC is a principle while DI is a way of implementing IOC. Unity is described as a lightweight, extensible dependency injection container. Lets see when and why to use Unity Framework?

UNITY Framework removes Tight Coupling of Classes and Objects and make them loosely coupled. UNITY Framework facilitates the design and implementation of loosely coupled, reusable, and testable objects in your software designs by removing dependencies. Using dependency injection will make the application  more flexible to changes and more maintainable.  Instead of compile time dependencies, UNITY Framework offers runtime loading and initialization of components, which makes solutions load on demand.

Example of Dependency and Tight Coupling

Consider the below example. We have a Customer class which contains an Address class object. The biggest issue with the code is tight coupling between classes. In other words the customer class depends on the address object. So for any reason address class changes, it will lead to change and compiling of Customer class also. So, if for any reason the address object is not able to create, the whole customer class will fail in the constructor initialization itself. 

public class Customer
{
      private Address address;
      public Customer()
      {
           address = new Address();
      }
}

Ways to implement Dependency Injection

In DI, we have four broader ways to implement Dependency Injection:

1. Constructor way
2. Exposing setter and getter
3. Interface implementation
4. Service locator


Why to use Unity?

1. It provides simplified object creation, especially for hierarchical object structures and dependencies, which simplifies application code.

2. It supports abstraction of requirements; this allows developers to specify dependencies at run time or in configuration and simplify management of crosscutting concerns.

3. It increases flexibility by deferring component configuration to the container.

4. It has a service location capability; this allows clients to store or cache the container. This is especially useful in ASP.NET Web applications where developers can persist the container in the ASP.NET session or application.

When to Use Unity?

1. You have dependencies between objects.

2. The dependencies are complex and you need a way to abstract them.

3. You want to be able to change your dependencies at runtime.

4. You want to use constructors, properties or method calls injections.


Further Reading: 

http://www.c-sharpcorner.com/uploadfile/questpond/design-pattern-inversion-of-control-and-dependency-injection/
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/inversion-of-control/
http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/unity-framework/
http://msdn.microsoft.com/en-us/library/ff649614.aspx

How to count number of data members in a C# class at runtime?

How to count number of data members in a C# class at runtime?
 
While development of one of my C# .NET project, I felt the need to count the number of data members at runtime and do something with them. I used typeof(ClassName).GetFields().Length to solve the problem like following.
 
using System;

public class Test
{
        public static void Main()
        {
                var count = typeof(ABC).GetFields().Length;
                Console.WriteLine(count);
        }
}

static class ABC
{
  public static int A;
  public static int B;
  public static int C;
}
 
If you have any better approach to solve the above problem, please update me.

Wednesday, 1 May 2013

Attached Properties in WPF: Special Kind of Dependency Properties


Attached Properties in WPF: Special Kind of Dependency Properties

Attached properties are a special kind of DependencyProperties. They allow you to attach a value to an object that does not know anything about this value.

A good example for this concept are layout panels. Each layout panel needs different data to align its child elements. The Canvas needs Top and Left, The DockPanel needs Dock, etc. Since you can write your own layout panel, the list is infinite. So you see, it's not possible to have all those properties on all WPF controls.

The solution are attached properties. They are defined by the control that needs the data from another control in a specific context. For example an element that is aligned by a parent layout panel.

To set the value of an attached property, add an attribute in XAML with a prefix of the element that provides the attached property. To set the the Canvas.Top and Canvas.Left property of a button aligned within a Canvas panel, you write it like this:

<Canvas>
    <Button Canvas.Top="20" Canvas.Left="20" Content="Click me!"/>
</Canvas>

public static readonly DependencyProperty TopProperty =
    DependencyProperty.RegisterAttached("Top", 
    typeof(double), typeof(Canvas),
    new FrameworkPropertyMetadata(0d,
        FrameworkPropertyMetadataOptions.Inherits));

public static void SetTop(UIElement element, double value)
{
    element.SetValue(TopProperty, value);
}

public static double GetTop(UIElement element)
{
    return (double)element.GetValue(TopProperty);
}

Dependency Property and Dependency Object: Difference between Dependency Property and CLR Property

Dependency Property and Dependency Object: Difference between Dependency Propery and CLR Property

Dependency properties belong to one class but can be used in another. Consider the code snippet below:

<Rectangle Height="72" Width="131" Canvas.Left="74" Canvas.Top="77" /> 

Height and Width are regular properties of the Rectangle. But Canvas.Top and Canvas.Left are dependency properties as they belong to the Canvas class. It is used by the Rectangle to specify its position within Canvas.

Dependency Property is defined as static. So Dependency Property is maintained at class level. The wrapper class which can create a Dependency property is called a DependencyObject. To work with dependency property, you must derive the class from DependencyObject

Difference between Dependency property and CLR property

CLR property is just a wrapper around private variables. It uses Get / Set methods to retrieve and store value of a variable into it. CLR property gives you only one block in which you can write code to invoke whenever a property is get or set. Hence CLR property system is fairly straightforward.

On the other hand, the capabilities of Dependency property system is huge. The idea of Dependency property is to compute the value of the property based on the value of other external inputs. The external inputs might be styles, themes, system properties, animations, etc. So, you can say a dependency property works with most of the WPF inbuilt features that were introduced.

Advantages of Dependency Property

1. Property Value Inheritance: By Property Value Inheritance, we mean that value of a Dependency property can be overridden in the hierarchy in such a way that the value with highest precedence will be set ultimately.

2. Data Validation: We can impose Data Validation to be triggered automatically whenever the property value is modified.

3. Participation in Animation: Dependency property can animate. WPF animation has lots of capabilities to change value at an interval. Defining a dependency property, you can eventually support Animation for that property.

4. Participation in Styles: Styles are elements that define the control. We can use Style Setters on Dependency property.

5. Participation in Templates: Templates are elements that define the overall structure of the element. By defining Dependency property, we can use it in templates.

6. DataBinding: As each of the Dependency properties itself invoke INotifyPropertyChanged whenever the value of the property is modified, DataBinding is supported internally. 

7. CallBacks: You can have callbacks to a dependency property, so that whenever a property is changed, a callback is raised.

8. Resources: A Dependency property can take a Resource. So in XAML, you can define a Resource for the definition of a Dependency property.

9. Metadata overrides: You can define certain behavior of a dependency property using PropertyMetaData. Thus, overriding a metadata form a derived property will not require you to redefine or re implementing the whole property definition.

10. Designer Support: A dependency property gets support from Visual Studio Designer. You can see all the dependency properties of a control listed in the Property Window of the Designer.

How To Define a Dependency Property

public static readonly DependencyProperty MyCustomProperty = 
DependencyProperty.Register("MyCustom", typeof(string), typeof(Window1));
public string MyCustom
{
    get
    {
        return this.GetValue(MyCustomProperty) as string;
    }
    set
    {
        this.SetValue(MyCustomProperty, value);
    }
}

In the above code, I have simply defined a Dependency property. Dependency property is declared as static and maintained in class level, so you may say Class A to have a property B. So property B will be maintained to all the objects that class A have individually. The Dependency property thus creates an observer for all those properties maintained by class A and stores it there. Thus it is important to note that a Dependency property should be maintained as static.

The naming convention of a dependency property states that it should have the same wrapper property which is passed as the first argument. Thus in our case, the name of the Wrapper "MyCustom" which we will use in our program should be passed as the first argument of the Register method, and also the name of the Dependency property should always be suffixed with Property to the original Wrapper key. So in our case, the name of the Dependency Property is MyCustomProperty. If you don't follow this, some of the functionality will behave abnormally in your program.

It should also be noted that you should not write your logic inside the Wrapper property as it will not be called every time the property is called for. It will internally call the GetValue and SetValue itself. So if you want to write your own logic when the dependency property is fetched, there are callbacks to do them.

Sources: