Saturday, 4 May 2013

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: 

Common Logical Questions Asked in a Technical Interview

Common Logical Questions Asked in a Technical Interview

Well, if you are going for a technical interview in any programming language, in any stream, irrespective of your expertise and experience, you could be asked very simple logical questions which you must know. Interviewer can ask you very basic and famous C programs to check your logic which you had done in very early stage of your life like Fibonacci Series, Factorial Number, Palindrome Number, Prime Numbers etc. You should be able to write down the logic of these basic programs in a minute otherwise it might be very embarrassing for you and will put direct negative impact on the interviewer.

All your domain knowledge, programming language hold could be negated if you get stuck in these problems. So I must advise you to have a quick look on these algorithms before you appear in any technical interview.

Fibonacci Series: To print Fibonacci series up to n numbers

int main()
{
   int n, first = 0, second = 1, next, c;

   printf("Enter the number of terms\n");
   scanf("%d",&n);

   printf("First %d terms of Fibonacci series are :-\n",n);

   for ( c = 0 ; c < n ; c++ )
   {
      if ( c <= 1 )
         next = c;
      else
      {
         next = first + second;
         first = second;
         second = next;
      }
      printf("%d\n",next);
   }
   return 0;
}

Factorial Program: To find out factorial of a number 

int main()
{
  int c, n, fact = 1;

  printf("Enter a number to calculate it's factorial\n");
  scanf("%d", &n);

  for (c = 1; c <= n; c++)
    fact = fact * c;

  printf("Factorial of %d = %d\n", n, fact);

  return 0;
}

Palindrome Number: To check whether a given number is palindrome or not?

int main()
{
   int n, reverse = 0, temp;

   printf("Enter a number to check if it is a palindrome or not\n");
   scanf("%d",&n);

   temp = n;

   while( temp != 0 )
   {
      reverse = reverse * 10;
      reverse = reverse + temp%10;
      temp = temp/10;
   }

   if ( n == reverse )
      printf("%d is a palindrome number.\n", n);
   else
      printf("%d is not a palindrome number.\n", n);

   return 0;
}

Prime Number: To check whether a given number is prime number or not?

int isPrime(int);

int main(){

    int num,prime;

    printf("Enter a positive number: ");
    scanf("%d",&num);

    prime = isPrime(num);

   if(prime==1)
        printf("%d is a prime number",num);
   else
      printf("%d is not a prime number",num);

   return 0;
}

int isPrime(int num){

    int i=2;

    while(i<=num/2){
         if(num%i==0)
             return 0;
         else
             i++;
    }

    return 1;
}

Please do add some more basic programs or algorithms you need to know before going to a technical interview.

Types of Routed Events in WPF

Types of Routed Events in WPF
 
The concept of Routed Events comes into the picture when we want to handle an event, that is originated from some other control in the hierarchy.  Say for example if any user clicks the button control, that event which is normally a button_click event, can be raised by button, label, gird or window.
 
Types of Routed Events:
 
WPF defines most routed events in pairs - one tunnelling and the other bubbling.
 
1. Direct Events
2. Bubbling Events
3. Tunneling Events
 
1.  Direct Events:
 
Direct Events are very well known to .NET people who has worked on standard .NET controls.  A direct event get raised by the control itself. Say for example button_click event which got raised by the button control itself.
 
2.  Bubbling Events:
 
Bubbling events are first raised by the control and then are raised by the controls in that control's hierarchy. Say in a window, we have a grid and in that we have a button control. Now if button is clicked, first it will raise button_click event, then the grid event and at last the window event.
 
3.  Tunneling Events:
 
The Tunneling Events are the opposite of the bubbling events as they are raised first by the root element in the hierarchy and then by the child elements. Same as our previous example, first window event will get raised, followed by the grid event and at last the button_click event.
 
The tunnelling event name always begins with 'Preview' and is raised first. This gives parents the chance to see the event before it reaches the child. This is followed by the bubbling counterpart. In most cases, you will handle only the bubbling one.
 
Example of Routed Events
 
Routed Events provide the ability for different controls in the element tree to react to events.
For instance, if we have a Window containing a StackPanel containing a Button and someone presses the mouse key on the button, the events will be fired in this order:
 
PreviewMouseDown on Window
PreviewMouseDown on StackPanel
PreviewMouseDown on Button
MouseDown on Button
MouseDown on StackPanel
MouseDown on Window
 
Example with code
 
XAML file:
 
<Grid Button.Click="Grid_Click">
    <StackPanel Button.Click="StackPanel_Click">
        <Button Content="Click Me!" Height="35" Width="150"
        Margin="5" />
    </StackPanel>
</Grid>
 
CodeBehind file:
 
private void StackPanel_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Stackpanel");
}
 
private void Grid_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Grid");
}
 
Now when button is clicked, following messages will appear in sequence
Stackpanel
Grid