Tuesday, April 16, 2013

True difference between Hast Table and Dictionary

S.No.

Dictionary

Hash Table

1

A dictionary is a data structure that maps keys to values.

A hash table is a data structure that maps keys to values by taking the hash value of the key (by applying some hash function to it) and mapping that to a bucket where one or more values is stored.

2

Dictionary is not a threadsafe.

Hashtable is threadsafe.

3

Dictionary is types means that the values need not to boxing.

Hashtable values need to be boxed or unboxed because it stored the values and keys as objects.        

4

When you try to get the value of key which does not exists in the collection, the dictionary throws an exception of 'KeyNotFoundException'.

When you try to get the value of key which does not exists in the collection, the Hashtable returns a NULL value.

5

When using large collection of key value pairs dictionary is not as good as Hashtable.

When using large collection of key value pairs hashtable would be considered more efficient than dictionary.

6

When we retrieve the record in collection the dictionary maintains the order of entries by which entries were added.

When we retrieve the record in collection the hashtable does not maintain the order of entries.

7

Dictionary relies on chaining.

Hashtable relies on rehashing.

8

Dictionary is Abstract Base class of Hash Table.

Hash Table is Derived by Dictionary class.

9

Dictionary is Generic Type.

Hash Table is not generic type.

 

What is Dependency Property in WPF?

Represents a property that can be set through methods such as, styling, data binding, animation, and inheritance.

A DependencyProperty supports the following capabilities in Windows Presentation Foundation (WPF):
  • The property can be set in a style.
  • The property can be set through data binding.
  • The property can be set with a dynamic resource reference.
  • The property can inherit its value automatically from a parent element in the element tree.
  • The property can be animated.
  • The property can report when the previous value of the property has been changed and the property value can be coerced.
  • The property reports information to WPF, such as whether changing a property value should require the layout system to recompose the visuals for an element.
  • The property receives support in the WPF Designer for Visual Studio.

WPF interview Questions

WPF Interview Questions – WPF
Level 1
  1. Q: What the first class that is loaded by any new WPF Application project?
    A: App. App.xaml and App.xaml.cs.
  2. Q: What is a DependencyProperty?
    A: Represents a property that can be set through methods such as, styling, data binding, animation, and inheritance. [1]
  3. Q: Name as many layout controls as you can:
    A: Grid, DockPanel, Canvas, WrapPanel, UniformGrid, StackPanel
  4. Q: What tool should you use sketch a mock of your WPF application?
    A: SketchFlow
Level 2
  1. Q: Describe how you would go about writing your own button style?
    A: Make sure the interviewee understands the following:
    - How to copy the default style using Expression Blend.
    - How to change the style
    - How there must be a Style for each state: Enabled, Disabled, Mouseover, pushed, etc…
  2. Q: You need to display a list of items. Which controls are possible options? Of those, which would you use and why?
    A: ItemsControl, ListBox, ListView, DataGrid.
    - Make sure they know that ListBox and ListView can be selected while ItemsControl does not support selection.
    - ListView is more feature rich, as it inherits ListBox, which inherits ItemsControl, and adds features.
    - Make sure they understand what a DataGrid is and how it is different and why they would display a list in a DataGrid.
  3. Q: What can you do in Expression Blend that you cannot do in Visual Studio?
    A: Configure brushes and gradient brushes in the Properties window.
    A: Configure Visual States.
    A: Configure sample data.
    A: Configure Object Timelines
    A: Animation
    A: Many design features…
  4. What can you do in Visual Studio that you cannot do in Expression Blend?
    A: Reformat source code, including XAML, with a hot key.
    A: Include Solution Folders.
Level 3
  1. What are common Localization/Globalization practices for Localizing/Globalizing WPF?
    A: 1) Use Resources.resx, 2) Use BAML, 3) Use a ResourceDictionary to manage localizable strings.
  2. Q: What are some best practices when using WPF if you plan to build a Localized/Globalized application?
    A: Write UI in XAML
    A: Avoid sizing and positionings, but let objects automatically flow.
    A: Enable TextWrapping.
WPF Interview Questions – Binding
Level 1
  1. Q: How do you bind a bool value to Visibility?
    A: Add a BoolToVisibilityConverter to your resources and then use it as the converter in your Binding.
  2. Q: What is IValueConverter used for?
    A: So that a control or control property can be bound to an element of any data type and the conversion happens in the binding process.
  3. Q: Here is a TextBox.  Change it so that it will bind to the ‘Text’ property of any DataContext.
    <TextBox  />
    A: <TextBox Text=”{Binding Path=Text}” />
  4. Q: What happens if the value you are binding to does not exist?
    A: The error is ignored. If running from Visual Studio, a message is logged in the Output window.
Level 2
  1. You want to use a custom Binding but the control does not support binding in the area you want. What are your options? Which would you choose and why?
    A1: Inherit object and add a Dependency Property – If the object is not sealed this is likely an easier option.
    A2: Create an attached property – The object might be sealed.
  2. Q: How do you bind a button’s Command property to a method?
    A: You don’t. You bind to an ICommand. You create a class that implements ICommand and in that object you connect to your method.
  3. Q: Provide an example of when and why you would use MultiBinding.
    A: When you have multiple values that your which to combine.
    A: When you want to use String.Format in XAML.
  4. Q: What is the Binding syntax for binding to a Static value?
    A:  {x:Static s:MyStaticClass.StaticValue2}
Level 3
  1. Q: Provide a situation in which you have or would use a ConverterParameter.
    A: Any time you have a converter that returns something different based on a parameter.
    A: Look for them to share an example of needing to do this.
  2. What is the correct syntax for binding to a property of a Singleton?
    A: {Binding Source={x:Static sing:MySingletonClass.Instance}, Path=SomeProperty}
WPF Interview Questions – MVVM
Level 1
  1. Q: What is INotifyPropertyChanged used for?
    A: For notifying any observer, usually a WPF control, that the property it is bound to has changed.
  2. Q: What is the purpose of MVVM?
    A: To provide a design pattern that allows for separation of concerns. The UI is independent of the data and the data is independent of the UI.
  3. Do you prefer and MVVM framework or just a few MVVM objects?
    A: No real right answer here, just checking how they actually have implemented MVVM.
  4. Q: What object do most ViewModels inherit from:
    A: Either ObservableObject or ViewModelBase.
  5. Q: How do you implement binding a button click to a method?
    A: Create a class that implements ICommand, often called RelayCommand or RoutedCommand.
    Add an ICommand property to your ViewModel and instantiate the property using your ICommand implementation, RelayCommand or RoutedCommand.
Level 2
  1. What gotchas have you experience while using the MVVM pattern?
    A: No real answer here…just that they have experienced problems proves their experience. Example issues:
    - The ViewModel just becomes a place for all the code-behind.
    - Determining whether the View can, should, or should not reference the ViewModel.
    - Determining if View objects can, should, or should not be in the ViewModel.
    - When breaking Views down, how small to go.
    - When breaking ViewModels down, how small to go.
    - Should an object in the model implement ObservableObject?
  2. Q: Why is it better to use an IValueConverter instead of  performing the conversion in the ViewModel?
    A: This follows the Don’t Repeat Yourself (DRY) principle. It also follows the Single Responsibility Principle (SRP).
    Because you may have to perform the same conversion between multiple View and ViewModel combinations. If each ViewModel has the code, the code is duplicated. If the code is in an IValueConverter, it exists in one place and is resusable.
Level 3
  1. Q: What does this command do and when would you use it? CommandManager.InvalidateRequerySuggested()
    A: It causes the any commands, such as a binding to Button.Command to check again if it can execute.
    It is used when the command runs and the button should be enabled when the command completes, but the button stays disabled. This often occurs when running the command on a thread or by using a BackgroundWorker.
  2. Q: When should you use “code-behind” in MVVM.
    Note: Don’t except ‘never’ as an answer.
    A: When the code only involves the View or WPF Controls in the View.
    A: When you need to implement events that do not support binding to ICommand.

Thursday, April 4, 2013

How to call Commands from UI Control in MVVM pattern

We will use RelayCommands to register Execute and CanExcute command handlers in MVVM pattern.
To achieve this we will create a class RelayCommand.

    /// <summary>
    /// To register commands in MMVM pattern
    /// </summary>
    public class RelayCommand : ICommand
    {
        readonly Action<object> _execute;
        readonly Predicate<object> _canExecute;

        /// <summary>
        /// Constructer takes Execute events to register in CommandManager.
        /// </summary>
        /// <param name="execute">Execute method as action.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
            try
            {
                if (null == execute)
                {
                    throw new NotImplementedException("Not implemented");
                }

                _execute = execute;
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Constructer takes Execute and CanExcecute events to register in CommandManager.
        /// </summary>
        /// <param name="execute">Execute method as action.</param>
        /// <param name="canExecute">CanExecute method as return bool type.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            try
            {
                if (null == execute)
                {
                    _execute = null;
                    throw new NotImplementedException("Not implemented");
                }

                _execute = execute;
                _canExecute = canExecute;
            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// Can Executed Changed Event
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                CommandManager.RequerySuggested += value;
            }
            remove
            {
                CommandManager.RequerySuggested -= value;
            }
        }

        /// <summary>
        /// Execute method.
        /// </summary>
        /// <param name="parameter">Method paramenter.</param>
        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        /// <summary>
        /// CanExecute method.
        /// </summary>
        /// <param name="parameter">Method paramenter.</param>
        /// <returns>Return true if can execute.</returns>
        public bool CanExecute(object parameter)
        {
            return _canExecute == null ? true : _canExecute(parameter);
        }
    }


Now in MVVM pattern we need to declare a command in View Model that will be bind with the Command property of the WPF Control.

We will create a ICommand property and in get section will register the Execute and CanExecute handlers for the command. The arguments “Param” would be used for Command Parameter.

        ICommand _saveSettingsCommand;

        public ICommand SaveSettingsCommand
        {
            get
            {
                if (_saveSettingsCommand == null)
                    _saveSettingsCommand = new RelayCommand(param => this.SaveSettingsCommand_Execute(param), param => this.SaveSettingsCommand_CanExecute(param));
                return _saveSettingsCommand;
            }
        }

        bool SaveSettingsCommand_CanExecute(object param)
        {
            return true;
        }

        void SaveSettingsCommand_Execute(object param)
        {
            if (_applicationVM == null || _configurationLabwareVM == null || !_isEditable)
                return;
            Configure(!IsSelected);
        }


This is done!
Now just call this command from the control in the view which is bounded with the view model where this command defined.
The Command Binding will look like this.

<telerik:RadButton Grid.Column="1"
                   Name="radButton1"
                   MinWidth="70"
                   HorizontalAlignment="Stretch"
                   VerticalAlignment="Center"
                   Background="{Binding StatusBrush}"
                   Height="20"
                   Command="{Binding SaveSettingsCommand}"
                   CommandParameter="{Binding LabwareID}"
                   >


Go through the steps I defined above. It is very easy to work with commands in WPF.
Enjoy!!!