Monday, September 15, 2014

Parking lot

ASP.NET MVC
 > Building ASP.NET MVC 4 ( 7 h)
 >TDD and ASP.NET MVC - 1h
 > Best practices of ASP.NET MVC - 45m
 > Leveraging the ASP.NET
 > Practical IoC With ASP.NET MVC/unity 20
 > ASP.NET Security ( 1 h)

ASP.NET MVC Validation
 http://rachelappel.com/asp-net-mvc/how-data-annotations-for-asp-net-mvc-validation-work/
http://www.codeproject.com/Articles/422573/Model-Validation-in-ASP-NET-MVC

Web API
 ASP.NET Web API Security Architecture  (50 m)
 Authorization ( 50 m)
 Implementing an API in ASP.NET Web API ( 4 h )

Multi - Threading

WPF
Converting events to commands (Routed Events/Attached Properties)
http://msdn.microsoft.com/en-us/library/ms742806(v=vs.110).aspx
http://blog.magnusmontin.net/2013/06/30/handling-events-in-an-mvvm-wpf-application/
http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html
http://www.codeproject.com/Tips/478643/Mouse-Event-Commands-for-MVVM


Wednesday, September 10, 2014

WPF Code

public interface ICacheProvider
    {
        /// <summary>
        /// Retrieve cached item
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="key">Name of cached item</param>
        /// <param name="value">Cached value. Default(T) if
        /// item doesn't exist.</param>
        /// <returns>Cached item as type</returns>
        bool Get<T>(string key, out T value);

        /// <summary>
        /// Insert value into the cache using  appropriate name/value pairs
        /// </summary>
        /// <typeparam name="T">Type of cached item</typeparam>
        /// <param name="value">Item to be cached</param>
        /// <param name="key">Name of item</param>
        void Set<T>(string key, T value);
    }

  public class CacheProvider : ICacheProvider
    {
        private readonly MemoryCache _memoryCache;
        private readonly CacheItemPolicy _cacheItemPolicy;

        public CacheProvider(CacheItemPolicy cacheItemPolicy, string configurationName,   NameValueCollection config = null)
        {
            _memoryCache = ( config != null )? new MemoryCache(configurationName, config) : new MemoryCache(configurationName);
            _cacheItemPolicy = cacheItemPolicy;
        }

        public bool Get<T>(string key, out T value)
        {
            bool result = false;
            value = default(T);
            object item = _memoryCache.Get(key);
            if (item != null)
            {
                value = (T)item;
                result = true;
            }

            return result;
        }

        public void Set<T>(string key, T value)
        {
            _memoryCache.Set(key, value, _cacheItemPolicy);
        }
    }

  class Program
    {
        static void Main(string[] args)
        {
            //Fund fund = new Fund() { Id =1, Code = "MSREF1", Name = "MS REF I"};
            IList<Fund> funds = new List<Fund>()
            {
                new Fund() { Id =1, Code = "MSREF1", Name = "MS REF I"},
                new Fund() { Id =1, Code = "MSREF2", Name = "MS REF II"},
                new Fund() { Id =1, Code = "MSREF3", Name = "MS REF III"},
                new Fund() { Id =1, Code = "MSREF4", Name = "MS REF IV"},
                new Fund() { Id =1, Code = "MSREF5", Name = "MS REF V"},
                new Fund() { Id =1, Code = "MSREF6", Name = "MS REF VI"}
            };
            var policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(60.0)};
            var cachingProvider = new CacheProvider(  policy,  "FundCacheConfig");
            cachingProvider.Set("funds", funds);

            IList<Fund> cachedFunds = null;
            bool status = cachingProvider.Get("funds", out cachedFunds);
            Console.WriteLine(String.Format("Funds => status {0} ", status ));
            if (status)
            {
                foreach (var fund in cachedFunds)
                    Console.WriteLine(String.Format("Funds => Id {0} Code : {1} , Name : {2}  ", fund.Id, fund.Code, fund.Name));
            }
            Console.ReadLine();
        }
    }

    public class Fund
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Name { get; set; }
    }

WPF Interview Questions

Name as many layout controls as you can:
A: Grid, DockPanel, Canvas, WrapPanel, UniformGrid, StackPanel.
StackPanel has an Orientation Property for horizontal or vertial alignment

What controls have you worked in WPF
TabGrid, DataGrid, Drop downs, List Boxes, etc.

Describe how you would go about writing your own button style?

ou need to display a list of items. Which controls are possible options? Of those, which would you use and why?
 ItemsControl, ListBox, ListView, DataGrid.

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.

What is the Binding syntax for binding to a Static value?

Provide a situation in which you have or would use a ConverterParameter.
Tri State Values

When should you use “code-behind” in MVVM.
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.

What is the difference between xmlns and xmlns:x in WPF ?
The first namespace is the default namespace and helps to resolve overall WPF elements.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

The second namespace is prefixed by “x:” and helps to resolve XAML language definition.
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:name : is used to define an object instance

What are the different ways of defining ViewModels in a WPF View ?

1) Import namespace where the class resides
<Window x:Class="LearnWpfResources.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:custns="clr-namespace:LearnWpfResources"
        Title="MainWindow" Height="350" Width="525">

2) Create an object
<Window.Resources>
<custns:Customer x:Key="custobj"/>
</Window.Resources>

3) Bind a property of the object to a control.
<TextBox Text="{Binding CustomerCode, Mode=TwoWay, Source={StaticResource custobj}}" />

What are contentpresenter ?

Difference between UI / Framework Element ?

Explain WPF relative binding / relative resource?
When we define bindings we need at least two elements target and source. But many times rather than defining binding between two elements we would like to define binding with reference to the current element i.e. RELATIVELY.

For instance let’s say we have a WPF border and we would like height and width of the broder to be same. So for this scenario the target and source are the same, the WPF border itself.

<Border BorderBrush="Black" BorderThickness="1" Height="139"Width="{Binding Height,  RelativeSource={RelativeSource Self}}"/>

Property Description
AncestorType Which type of parent element is it?. Is it a border element , grid element etc.
AncestorLevel An element can have multiple parents. For example in the above XAML we have two parents one with red color and the other with green. So this property specifies which level of parent element we want to refer. Below is the figure which depicts the levels. The red color border is level 1 and the green color border is level 2.
Binding This specifies which property we want to bind to. For the current example we want to bind to border’s brush color.

<Border BorderBrush="DarkGreen">
<Border BorderBrush="DarkRed”>
<TextBox />
</Border>
</Border>
<TextBox  Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel=1, AncestorType={x:Type Border}}}"/>

Style Triggers
============
Want a style property to execute under certain conditions

<Style x:Key="myStyle" TargetType="Button">
<Style.Triggers>
        <Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Red"/>
</Trigger>
    </Style.Triggers>
<Setter Property="Background" Value="Aqua" />
</Style>

Routed Events
----------------
A routed event is a type of event that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event

Markup Exstensions
The following are the built-in markup extensions: 

1)Binding:-To bind the values of two properties together. 

2)StaticResource:-One time lookup of a resources entry 

3)DynamicResource:-Auto updating lookup of a resource entry 

4)TemplateBinding:-To bind a property of a control template to a dependency property of the control 

5)x:Static:-Resolve the value of a static property. 

6)x:Null:-Return null

Difference between control and Data Templates ?
A DataTemplate, therefore, is used to provide visual structure for underlying data, while a ControlTemplate has nothing to do with underlying data and simply provides visual layout for the control itself.

What is content presenter ?
CONTENT PRESENTER: Content Presenter in WPF is used inside control templates, as well as inside the root application markup. The concept of ContentPresenter is quite simple – it is a placeholder for any XAML content and it can be used to insert content at runtime. Or we can say that ContentPresenter is a class that will automatically take the content of the ContentControl and display it, when placed into a ContentControl's ControlTemplate. 

A content presenter is used via the ContentPresenter element:
<ContentPresenter></ContentPresenter> 

Syntax: 
<ContentPresenter Name="MyContent">
   <ContentPresenter.Content>
      <Button>Click Me</Button>
   </ContentPresenter.Content>

</ContentPresenter>

Use Practical Examples of Routed/Attached Events/Dependency Property/Attached properties in the financial domain


C#
====
When would you use partial and why ?

WPF Data Validation

Create a Control Template
<ControlTemplate x:Key="validationErrorTemplate">
    <DockPanel>
        <TextBlock Foreground="Red"
            DockPanel.Dock="Top">!</TextBlock>
        <AdornedElementPlaceholder
           x:Name="ErrorAdorner"
        ></AdornedElementPlaceholder>
    </DockPanel>
</ControlTemplate>

Create a Validation Rule
public class NameValidator : ValidationRule
{
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        if (value == null)
            return new ValidationResult(false, "value cannot be empty.");
        else
        {
            if (value.ToString().Length > 3)
                return new ValidationResult
                (false, "Name cannot be more than 3 characters long.");
        }
        return ValidationResult.ValidResult;
    }
}

Plug the Validation Control Template with the control
<TextBox Height="23" HorizontalAlignment="Left"
              Grid.Column="1" Grid.Row="0" Name="textBox1"
              VerticalAlignment="Top" Width="120"
              Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
    <TextBox.Text>
        <Binding Path="Name" Mode="TwoWay" UpdateSourceTrigger="LostFocus">
            <Binding.ValidationRules>
                <local:NameValidator></local:NameValidator>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox> 

Thursday, September 4, 2014

data Modelling

Data Modelling
\http://www.agiledata.org/essays/dataModeling101.html

http://www.1keydata.com/datawarehousing/data-modeling-levels.html

Wednesday, September 3, 2014

Carrier Interviews

1) Database
Data Model a Security Database

1) Support Auditing
2) Support Archiving
3) UPSERT
4) Normalization

http://www.databasejournal.com/features/mssql/article.php/3739131/UPSERT-Functionality-in-SQL-Server-2008.htm

2) What are the concurrency issues faced on the database and app server side ? How do we resolve the same ?

3) Trannsaction Management on the App Server/Database side

4) Improve garbage collection performance
http://msdn.microsoft.com/en-us/library/windows/apps/hh994643.aspx
http://ashishkhandelwal.arkutil.com/csharp/how-to-improve-garbage-collection-performance/
http://www.codeproject.com/Articles/39246/NET-Best-Practice-No-Improve-garbage-collector

when should we be using finalize() method

Friday, August 29, 2014

.NET Collections - Deep Dive

1) The generic collections were introduced in .NET 2.0 in the System.Collections.Generic 2_ namespace. 
2) The generic collections are unsynchronized
3) concurrent read access (all writes done at beginning and never again) is always safe, but for concurrent mixed access you should either synchronize the collection or use one of the concurrent collections.

There are two kinds of generic collections

1) Associative : Associative collections store a value in the collection by providing a key that is used to add/remove/lookup the item
2) Non - Associative : They don't use keys to manipulate the collection but rely on the object itself being stored or some other means (such as index) to manipulate the collection

Associative Classes 


Dictionary<TKey,TVale>

The Dictionary<TKey,TVale> is probably the most used associative container class. The Dictionary<TKey,TValue> is the fastest class for associative lookups/inserts/deletes because it uses a hash table under the covers. The insert/delete/lookup time of items in the dictionary is amortized constant time - O(1) - which means no matter how big the dictionary gets, the time it takes to find something remains relatively constant

The SortedDictionary<TKey,TValue> is similar to the Dictionary<TKey,TValue> in usage but very different in implementation. The SortedDictionary<TKey,TValye> uses a binary tree under the covers to maintain the items in order by the key. As a consequence of sorting.


Non - Associative Classes


The List<T> is a basic contiguous storage container. Some people may call this a vector or dynamic array. Essentially it is an array of items that grow once its current capacity is exceeded. Because the items are stored contiguously as an array, you can access items in the List<T> by index very quickly. However inserting and removing in the beginning or middle of the List<T> are very costly because you must shift all the items up or down as you delete or insert respectively


There are several other Non - Associative generic collections like LinkedList<T>, Stack<T>, Queue<T>


The older non-generic collections like ArrayList,  are non-type-safe and in some cases less performant than their generic counterparts.



Concurrent Classes.

The concurrent collections are new as of .NET 4.0 and are included in the System.Collections.Concurrent namespace. These collections are optimized for use in situations where multi-threaded read and write access of a collection is desired.


  • ConcurrentQueue
    • Thread-safe version of a queue (FIFO).
  • ConcurrentStack
    • Thread-safe version of a stack (LIFO)
  • ConcurrentBag
    • Thread-safe unordered collection of objects.
    • Optimized for situations where a thread may be bother reader and writer.
    • BlockingCollection
  • ConcurrentDictionary
    • Thread-safe version of a dictionary.
    • Optimized for multiple readers (allows multiple readers under same lock).

  • BlockingCollection
    • Wrapper collection that implement producers & consumers paradigm.
    • Readers can block until items are available to read.
    • Writers can block until space is available to write (if bounded).

List<T> Examples 


List<int> list = new List<int>(); //Add
 list.Add(2);
 list.Add(3);
 list.Add(5);
 list.Add(7);
list.Remove(5); //Delete
List<int> list = new List<int>(new int[] { 19, 23, 29 }); 
//Find

 // Finds first element greater than 20
 int result = list.Find(item => item > 20);

 Console.WriteLine(result);
Dictionary
Dictionary<string, int> dictionary =
     new Dictionary<string, int>();
 dictionary.Add("cat", 2);
 dictionary.Add("dog", 1);
 dictionary.Add("llama", 0);
 dictionary.Add("iguana", -1);
KeyValuePair
KeyValuePair: Key and Value properties
When Dictionary, or any object that implements IDictionary, 
is used in a foreach-loop, it returns an enumeration.
foreach (KeyValuePair<string, int> pair in dictionary )
 {
     Console.WriteLine("{0}, {1}",
  pair.Key,
  pair.Value);
 }
Iterating using KeyValuePair is faster than using .keys or ,values.
List Vs Dictionary
1) it is faster to loop through all the elements in a List than in a Dictionary.
2) For lookups dictionary is faster
Arrays vs Dictionary
Arrays are faster in terms of lookups compared to Dictionary