Wednesday, 1 May 2013

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

Tuesday, 30 April 2013

ICommand Interface and RelayCommand Class in WPF MVVM


ICommand Interface and RelayCommand Class in WPF MVVM

ICommand Interface and RelayCommand Class in WPF are commonly used for binding. ICommand Interface and RelayCommand class is implemented in the ViewModel and is exposed to the view controls.

Every view in the app has an empty codebehind file, except for the standard code that calls InitializeComponent in the class's constructor. In fact, you could remove the views' codebehind files from the project and the application would still compile and run correctly. Despite the lack of event handling methods in the views, when the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Hyperlink, Button, and MenuItem controls displayed in the UI. Those bindings ensure that when the user clicks on the controls, ICommand objects exposed by the ViewModel execute. You can think of the command object as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

When a ViewModel exposes an instance property of type ICommand, the command object typically uses that ViewModel object to get its job done.

We will try to understand ICommand Interface and RelayCommand Class with following example.

Create a View and ViewModel like following:

View: Lets create the view first.  Three things to note in this view

1. In this view, I have included MyWPFSample namespace

xmlns:local="clr-namespace:MyWPFSample"

2. I have set datacontext of the winodw to the MainWindowViewModel class present in MyWPFSample namespace

<Window.DataContext>
    <local:MainWindowViewModel/>
</Window.DataContext>    

3. I have done binding of the command of the button with the ButtonCommand property of MainWindowViewModel class.

Command="{Binding ButtonCommand}"

<Window x:Class="MyWPFSample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:MyWPFSample"
        Title="MainWindow" Height="150" Width="370">
    <Window.DataContext>
        <local:MainWindowViewModel/>
    </Window.DataContext>
        <Grid>
        <Button Content="Click"
                Height="23"
                HorizontalAlignment="Left"
                Margin="77,45,0,0"
                Name="btnClick"
                VerticalAlignment="Top"
                Width="203"
                Command="{Binding ButtonCommand}"
                CommandParameter="Hai" />
    </Grid>
</Window>


ViewModel: ViewModel has namespace MyWPFSample, class as MainWindowViewModel and property as ButtonCommand. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using System.Windows;

namespace MyWPFSample
{
    class MainWindowViewModel
    {
        private ICommand m_ButtonCommand;
        public ICommand ButtonCommand
        {
            get
            {
                return m_ButtonCommand;
            }
            set
            {
                m_ButtonCommand = value;
            }
        }
        public MainWindowViewModel()
        {
            ButtonCommand=new RelayCommand(new Action<object>(ShowMessage));
        }
        public void ShowMessage(object obj)
        {
            MessageBox.Show(obj.ToString());
        }
    }
}

When the user clicks on buttons, the application reacts and satisfies the user's requests. This works because of bindings that were established on the Command property of Button displayed in the UI. The command object acts as an adapter that makes it easy to consume a ViewModel's functionality from a view declared in XAML.

RelayCommand Class

In this example RelayCommand class is used for implementing ICommad object. I think it's a simple and standard approach.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;

namespace MyWPFSample
{
    class RelayCommand : ICommand
    {
        private Action<object> _action;
        public RelayCommand(Action<object> action)
        {
            _action = action;
        }
        #region ICommand Members
        public bool CanExecute(object parameter)
        {
            return true;
        }
        public event EventHandler CanExecuteChanged;
        public void Execute(object parameter)
        {
            if (parameter != null)
            {
                _action(parameter);
            }
            else
            {
                _action("Hello World");
            }
        }
        #endregion
    }
}

ICommand and RelayCommand keep track whether or not commands are available. If commands are not available, then all controls associated with that command are disabled. For example using command controls like button can be disabled if CanExecute() returns false. The Code that executes when command is invoked and is located in Execute event. handler. 

INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF


INotifyPropertyChanged Interface and PropertyChangedEventHandler in WPF

The INotifyPropertyChanged interface is used to notify clients, typically binding clients, which a property value has changed. The INotifyPropertyChanged interface contains an event called PropertyChanged. Whenever a property on a ViewModel / Model  object has a new value, it can raise the PropertyChanged event to notify the WPF binding system of the new value. Upon receiving that notification, the binding system queries the property, and the bound property on some UI element receives the new value

public class MyClass:INotifyPropertyChanged
{
    private int _ID;
    private string _Name;

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public int ID
    {
        get
        {
            return _ID;
        }
        set
        {
            _ID = value;
            OnPropertyChanged("ID");
        }
    }
    public string Name
    {
        get
        {
            return _Name;
        }
        set
        {
            _Name = value;
            OnPropertyChanged("Name");
        }
    }
}

Sunday, 28 April 2013

Difference between Events and Commands in WPF MVVM Architecture

Difference between Events and Commands in WPF MVVM Architecture

Commands are very powerful and useful feature of WPF. Cut, Copy and Paste are basic inbuilt commands in WPF. Commands and Events are related to each other to a large extent but the main concern there is that events doesn't fit well into MVVM paradigm. So we generally prefer to use commands in WPF MVVM architecture. Commands provide a lot of advantages over events. Some of them are listed below:

1. Commands in WPF allow you to move the implementation of a command handler to the buisness layer.

2. You can bind WPF command in the view (XAML) and receive the event raised. This way you do not have to use code behind which is a no-no in MVVM.

3. In events an action is tightly coupled with its source and can't be reused freely; Using commands you can easily maintain various actions in a single place and reuse them anywhere in application.

4. Commands are similar to Events except we can associate any number of UI Controls or Input Gestures to a command and bind that command to a handler that is executed when control are activated or gestures are performed.

Saturday, 27 April 2013

Difference between WPF and Window Forms in .NET

Difference between WPF and Window Forms in .NET

I have been asked the difference between WPF and Window Forms. my times by my juniors whenever I suggest them to learn WPF. So, today I am trying to clear this doubt and make my opinions clear about this.

There are a lot of differences between WPF and Window Forms. WinForms is past and WPF is the latest technology equipped with advanced features which Window Forms lack. WPF supports UI, media, documents, hardware acceleration, vector graphics, scalability to different form factors, interactive data visualization, and superior content readability. Lets have a look on the features and benefits that WPF provides over the Window Forms.

1. WPF is a Vector Graphics based UI Presentation Layer

WPF is a vector graphics based UI presentation layer where WinForms is not. By being vector based, it allows the presentation layer to smoothly scale UI elements to any size without distortion.

2. Enhanced Custom Controls Support

WPF is also a composable presentation system, which means that pretty much any UI element can be made up of any other UI element. This allows you to easily build up complex UI elements from simpler ones.

3. Enhanced DataBinding Support

WPF is also fully databinding aware, which means that you can bind any property of a UI element to a .NET object (or a property/method of an object), a property of another UI element, or data. Yes, WinForms supports databinding but in a much more limited way.

4. WPF is "skinable" or "themeable"

WPF is "skinable" or "themeable", which means that as a developer you can use a list box because those are the behaviors you need but someone can "skin" it to look like something completely different.

Think of a list box of images. You want the content to actually be the image but you still want list box behaviors. This is completely trivial to do in WPF by simply using a listbox and changing the content presentation to contain an image rather than text.
 
5. Supports Window Forms

WPF does support Windows Forms and Windows Forms can be included in WPF project by adding dlls of Window Forms.

Conclusion:

WPF is a replacement for WinForms. What Window Forms can do, WPF can, but what WPF can do, Window Forms cannot do all.

Thursday, 25 April 2013

Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities


Types of Entities in Entity Framework: EntityObject, POCO, POCO Proxy and Self-Tracking Entities

There are four types of Entities in Entity Framework: 

1) EntityObject 
2) POCO (Plain Old CLR Object)
3) POCO Proxy 
4) Self-Tracking Entities

EntityObject

By default, the ADO.NET Entity Data Model tools generate EntityObject derived entities. When you work with EntityObject derived types, the object context manages the relationships between your objects, tracks changes as they occur, and supports lazy loading in the most efficient manner. However, the EntityObject derived types have strong dependency on the Entity Framework.

POCO (Plain Old CLR Object)

POCO class is the class which doesn’t depend on any framework unlike EntityObject specific base class. It is like any other normal .net class that is why it is called “Plain Old CLR Objects”. The Entity Framework enables you to use existing .net classes together with the data model without making any modifications to the existing .net classes. These POCO entities (also known as persistence-ignorant objects) support most of the same LINQ queries as EntityObject derived entities.

POCO Proxy

POCO Proxy is a runtime proxy class of POCO entity. POCO entity becomes POCO Proxy entity if it meets certain requirements to enable lazy loading proxy and instant change tracking. It adds some methods at runtime to your POCO class which does instant change tracking and lazy loading stuff. 

POCO entity should meet the following requirement to become POCO proxy:

1. A custom data class must be declared with public access.
2. A custom data class must not be sealed (Not Inheritable in Visual Basic)
3. A custom data class must not be abstract (Must Inherit in Visual Basic).
4. A custom data class must have a public or protected constructor that does not have parameters.
5. The class cannot implement the IEntityWithChangeTracker or IEntityWithRelationships interfaces because the proxy classes implement these interfaces.
6. The ProxyCreationEnabled option must be set to true.
7. Each navigation property must be declared as public, virtual

Difference between POCO and POCO Proxy Classes

Main difference between POCO and POCO Proxy lies in save changes mechanism. POCO entities use Snapshot mechanism. So before saving changes POCO entities, you must use DetechChanges method of ObjectContext to synchronize data with ObjectStateManager. Whereas POCO Proxy entities use instant change tracking. It synchronize with ObjectStateManager as soon as something changes in the POCO Proxy entity. So it’s more efficient than snapshot mechanism and you don’t have to use DetechChanges method of ObjectContext. Thus POCO Proxy has a same functionality as EntityObject.

Self-Tracking Entities

The EntityObject derived entities, POCO, and POCO proxy entities works well in application where the entity objects can be attached to the object context that handles change tracking on single tier. However, in n-tier application, you have to transfer entities to a tier where the object context is not available e.g. Business tier or presentation tier. So how to track changes and report those changes back to the object context? Answer is “self-tracking entities”. Self-tracking entities as its name suggests, can record changes to scalar, complex, and navigation properties on its own. Self-tracking entities do not depend on the Entity Framework so it can be transferred to other tier.  

Self-Tracking entities have additional change tracking functions and it implements IObjectWithChangeTracker and INotifyPropertyChanged interface. It also mark it as DataContract to be used in WCF services.