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
















Thursday, August 21, 2014

C# Advanced Concepts

The dynamic type enables the operations in which it occurs to bypass compile-time type checking. Instead, these operations are resolved at run time.

Thedynamic type simplifies access to COM APIs such as the Office Automation APIs


 dynamic dyn = 1;
        object obj = 1;

        // Rest the mouse pointer over dyn and obj to see their 
        // types at compile time.
        System.Console.WriteLine(dyn.GetType());
        System.Console.WriteLine(obj.GetType());

A compiler error is reported for the attempted addition of an integer and an object in expression obj + 3. However, no error is reported for dyn + 3. The expression that contains dyn is not checked at compile time because the type of dyn is dynamic.

XElement contactXML =
    new XElement("Contact",
        new XElement("Name", "Patrick Hines"),
        new XElement("Phone", "206-555-0144"),
        new XElement("Address",
            new XElement("Street1", "123 Main St"),
            new XElement("City", "Mercer Island"),
            new XElement("State", "WA"),
            new XElement("Postal", "68042")
        )
    );

dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
contact.Address = new ExpandoObject();
contact.Address.Street = "123 Main St";
contact.Address.City = "Mercer Island";
contact.Address.State = "WA";
contact.Address.Postal = "68402";

Use of  dynamic objects is the ability to create extensible objects - objects that start out with a set of static members and then can add additional properties and even methods dynamically.
dynamic expand = new ExpandoObject();

expand.Name = "Rick";
expand.HelloWorld = (Func<string, string>) ((string name) => 
{ 
    return "Hello " + name; 
});

Console.WriteLine(expand.Name);
Console.WriteLine(expand.HelloWorld("Dufus"));
So, if you need to handle a dynamic type: use dynamic and if you need to handle dynamic data such as XML or JSON: use ExpandoObject

Functional Programming

There are two programming paradigms

Imperative programming: telling the "machine" how to do something, and as a result what you want to happen will happen.
Declarative programming: telling the "machine" what you would like to happen, and let the computer figure out how to do it.

FP : Creating abstractions using functions . Creating Higher Value Functions.

E.g to find prime numbers odd numbers, even numbers all encompass three logics
1) Iterating
2) apply the test ( is a prime, or an odd number, etc
3) Generating the result

Functional programming is all about abstracting ! and # to another function

private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test)

imperative syle
var numbers = [1,2,3,4,5]
var doubled = []

for(var i = 0; i < numbers.length; i++) {
  var newNumber = numbers[i] * 2
  doubled.push(newNumber)
}

//Declarative style
.//map creates a new array from an existing array, where each element in the new array is created by passing the elements of the original array into the function passed to map (function(n) { return n*2 } in this case).
var numbers = [1,2,3,4,5]
var doubled = numbers.map(function(n) {
  return n * 2
})

console.log(doubled)

Functional programming is all about Declarative programming
The base concept in functional programming is functions.
In functional programming we need to create functions as any other objects, manipulate them, pass them to other functions, etc.

Define Function types
Assign values to function objects (references)

=> Define Function Types
Func<double, double> f = Math.Sin;

We can use Action and predicate also for Funtion Types
Action<string> println = Console.WriteLine;
Predicate<string> isEmptyString = String.IsNullOrEmpty;

=> Define Function Values
Func<double, double> f1 = Math.Sin;
Func<double, double> f2 = Math.Exp;
double y = f1(4) + f2(5); //y=sin(3) + exp(5)
f2 = f1;
y = f2(9); //y=sin(9)


E.g.
        private static int Count<T>(T[] arr, Predicate<T> condition)
        {
            int counter = 0;
            for (int i = 0; i < arr.Length; i++)
                if (condition(arr[i]))
                    counter++;
            return counter;
        }

string[] words = new string[] { "one", "two", "three", "", "" };
            int numberOfEmptyBookTitles = Count(words, String.IsNullOrEmpty);

            int[] numbers = new int[] {-1, 2, 3, 6, 8, -15 , -4};
            int numberOfNegativeNumbers = Count(numbers, x => x < 0);

            Console.WriteLine("numberOfEmptyBookTitles" + numberOfEmptyBookTitles);
            Console.WriteLine(" numberOfNegativeNumbers " + numberOfNegativeNumbers);

Advantages of using Functional programming

1) Code Reuse: We can now reuse our utility functions which will result in a much smaller code base to achieve the same results.
2) Ease of Testing: Debugging and testing is easier because each function is not at the mercy of the state of some external object that we have to worry about replicating with our test.
3) Concurrency: If we stick strictly to a functional programming style and make sure there are no side-effects, our code is thread-safe by default because each thread will only be accessing objects instantiated within it's own thread stack and so there will be no objects having two threads trying to access them at the same time.

Converting "using" blocks to functions.
public static void Use<T>(this T item, Action<T> action) where T:IDisposable
{
    using (item)
    {
        action(item);
    }
}

// functional call using our utility method
new Disposable().Use(d =>
{
    // do something with d;
});

Tuesday, August 12, 2014

JQuery

JQuery Templates
http://these-pretzels-are-making-me-thlrsty.blogspot.com/2010/08/client-side-data-binding-with-jquery.html
http://www.diplo.co.uk/blog/2011/3/1/using-jquery-templates-to-bind-to-json-data.aspx
http://weblogs.asp.net/scottgu/jquery-templates-and-data-linking-and-microsoft-contributing-to-jquery

Web API

Hello World
http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api

WebApi Crud
http://www.asp.net/web-api/overview/creating-web-apis/creating-a-web-api-that-supports-crud-operations

Attribute Routing in Web API 2
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2

Routing and Action Selection
http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-and-action-selection

Exception Handling in Web API
http://www.asp.net/web-api/overview/web-api-routing-and-actions/exception-handling

Performance Considerations between Web API and Wcf
http://blogs.msdn.com/b/fkaduk/archive/2014/01/07/rest-wcf-vs-webapi-throughput.aspx

Difference between WCF and Web API and WCF REST and Web Service
http://www.dotnet-tricks.com/Tutorial/webapi/JI2X050413-Difference-between-WCF-and-Web-API-and-WCF-REST-and-Web-Service.html

ASP.NET Web API parameter binding part 1 – Understanding binding from URI
http://www.strathweb.com/2013/04/asp-net-web-api-parameter-binding-part-1-understanding-binding-from-uri/


Thursday, July 31, 2014

Dictionary ex

   IDictionary<int, byte[]> meDictionary = new Dictionary<int, byte[]>();
            for (int i = 0; i < 1100; i++)
            {
                var memoryPressure = new byte[1024 * 1024 * 1];
                meDictionary.Add(i, memoryPressure);
            }
            var memoryUsageAtEnd = GC.GetTotalMemory(false);

            //Update
            foreach (KeyValuePair<int, byte[]> pair in meDictionary)
            {
                pair.Value = "";
            }

Monday, July 28, 2014

TPL Demo for BEAM

Focus Areas

Try to improve current multi threading program with having one load but running
Linear Processing,
Thread,QueueWorkUserItem, and
Parallel Processing in the same instance

1) Difference between a Thread & a Task
Illustrate with an example
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n

2) how to read of Task Values.
Compare it with Thread.QueueWorkUserItem or Async Delegates
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n

3) Thread Continuation
http://www.codeproject.com/Articles/159533/Task-Parallel-Library-of-n

4) how to cancel Tasks
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n

Illustrate with a Chained one.

5) How to handle Exceptions

using Try catch block
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n

6) Data Parallelism
Illustrate DataParallelismTest on X86( 2 Cores), X64 machines (8 cores)

7) Parallel LINQ
http://www.codeproject.com/Articles/161434/Task-Parallel-Library-of-n

7) Task Parallelism

5) Thread Pools - Deep Dive
http://www.danielmoth.com/Blog/New-And-Improved-CLR-4-Thread-Pool-Engine.aspx




Software Downloads

PRISM 5 Download
http://www.microsoft.com/en-us/download/confirmation.aspx?id=42537

Friday, July 25, 2014

MDT

--WorkUnit.cs

    public class WorkUnit
    {
        public int Id { get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public string FilePath { get; set; }
        public int ExecutionTimeForWorkUnit { get; set; }
    }

--WorkUnitManager.cs
    public class WorkUnitManager    {
        private List<WorkUnit> _tasks;
        public WorkUnitManager()
        {
        }

        public IList<WorkUnit> GenerateWorkUnits()
        {
            var filePath = ConfigurationManager.AppSettings["feedLocation"];
            var workUnits = new List<WorkUnit>();
            for (var i = 0; i < 2; i++)
            {
                var workUnit = new WorkUnit { Id = i, Code = "workUnit" + i, FilePath = filePath + @"\ModelData" + i + ".csv", ExecutionTimeForWorkUnit = ( i==0) ? 1000 :  2000 * i};
                workUnits.Add(workUnit);
            }
            return workUnits;
        }

        public bool Process(IList<WorkUnit> workUnits )
        {
            try
            {
                WaitHandle[] waitHandles = new WaitHandle[workUnits.Count];
                for (var i = 0; i < workUnits.Count; i++)
                    waitHandles[i] = new AutoResetEvent(false) ;
                int index = 0;
                foreach (var unit in workUnits)
                {
                    //starting the thread
                    int index1 = index;
                    WorkUnit unit1 = unit;
                    var thread = new Thread(parameter =>
                    {
                        ProcessWorkUnit(unit1);
                        ((AutoResetEvent) waitHandles[index1]).Set();
                    });
                    thread.Start(unit);
                    index++;
                }
                WaitHandle.WaitAll(waitHandles);
                return true;
            }
            catch(Exception exception)
            {
                return false;
            }
        }

        private void ProcessWorkUnit(WorkUnit workUnit)
        {
            //Thread.Sleep(workUnit.ExecutionTimeForWorkUnit);
            ModelManager modelManager = new ModelManager();
            modelManager.ProcessModel(workUnit);
            var threadId = Thread.CurrentThread.ManagedThreadId;
            string logMessage = string.Format("Work Unit processed  => {0} after {1} ms. on thread {2} ", workUnit.Code, workUnit.ExecutionTimeForWorkUnit, threadId);
            ApplicationLogger.Instance.Log(typeof(WorkUnitManager), "------------------------------Start : Work Unit Information---------------------------", LogLevel.Info);
            ApplicationLogger.Instance.Log(typeof(WorkUnitManager), logMessage, LogLevel.Info);
            ApplicationLogger.Instance.Log(typeof(WorkUnitManager), "------------------------------End : Work Unit Information---------------------------", LogLevel.Info);
        }
    }

--
public class Model
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string InvestmentCode { get; set; }
        public double FxRate { get; set; }
        public double DailyPnl { get; set; }
    }

public class ModelValidation
    {
        public string Id { get; set; }
        public int ModelId { get; set; }
        public bool IsValid { get; set; }
        public string Exception { get; set; }
    }

--ModelTransaction.cs
public class ModelTransaction
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public string InvestmentCode { get; set; }
        public int FundId { get; set; }
        public int InvestmentId { get; set; }
        public double FxRate { get; set; }
        public double DailyPnl { get; set; }
        public double RepPnl { get; set; }
    }

--
public enum LogLevel
    {
        Debug,
        Info,
        Warn,
        Error
    }

    public sealed class ApplicationLogger
    {
        private static readonly ApplicationLogger _instance = new ApplicationLogger();
        private static ILog logger;

        static ApplicationLogger()
        {
            XmlConfigurator.Configure();
        }

        public static ApplicationLogger Instance
        {
            get { return _instance; }
        }

        public void Log(Type type, string message, LogLevel logLevel)
        {
            logger = LogManager.GetLogger(type);
            switch (logLevel)
            {
                case LogLevel.Debug:
                    logger.Debug(message);
                    break;
                case LogLevel.Warn:
                    logger.Warn(message);
                    break;
                case LogLevel.Info:
                    logger.Info(message);
                    break;
                case LogLevel.Error:
                    logger.Error(message);
                    break;
            }
        }
    }

--ModelManager.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeSnippets.Shared;
using CodeSnippets.Shared.Domain;

namespace CodeSnippets.Domain
{
    public class ModelManager : IModelManager
    {
        private IList<Model> _models;
        private IList<ModelTransaction> _modelTransactions;
        public ModelManager()
        {
         
        }

        public bool ProcessModel(WorkUnit workUnit)
        {
            Stopwatch stopwatch = new Stopwatch();
            // Begin timing
            stopwatch.Start();

            var modelRepository = new ModelRepository();

            //Load Models
            _models = modelRepository.Load(workUnit.FilePath);
            stopwatch.Stop();
            string logMessage = string.Format(" Operation : Load List<Model> : {0}, Processing Time : {1}", workUnit.FilePath, stopwatch.Elapsed.Milliseconds);
            ApplicationLogger.Instance.Log(typeof(ModelRepository), logMessage, LogLevel.Info);
            stopwatch.Reset();

            //Transform Models
            stopwatch.Start();
            _modelTransactions = modelRepository.Transform(_models);
            stopwatch.Stop();
            logMessage = string.Format("    Operation : Transform List<Model> : {0}, Processing Time : {1}", workUnit.FilePath, stopwatch.Elapsed.Milliseconds);
            ApplicationLogger.Instance.Log(typeof(ModelRepository), logMessage, LogLevel.Info);
            stopwatch.Reset();

            //Compute Models
            stopwatch.Start();
            modelRepository.Compute(_modelTransactions);
            stopwatch.Stop();
            logMessage = string.Format("    Operation : Compute RepPnL : {0}, Processing Time : {1}", workUnit.FilePath, stopwatch.Elapsed.Milliseconds);
            ApplicationLogger.Instance.Log(typeof(ModelRepository), logMessage, LogLevel.Info);
            stopwatch.Reset();

            //Enrich Models
            stopwatch.Start();
            modelRepository.Enrich(_modelTransactions);
            stopwatch.Stop();
            logMessage = string.Format("    Operation : Enrich Model Transactions : {0}, Processing Time : {1}", workUnit.FilePath, stopwatch.Elapsed.Milliseconds);
            ApplicationLogger.Instance.Log(typeof(ModelRepository), logMessage, LogLevel.Info);
            stopwatch.Reset();
            return true;
        }

        public IList<Model> GetModels()
        {
            return _models;
        }

        public IList<ModelTransaction> GetModelTransactions()
        {
            return _modelTransactions;
        }
    }
}

--ModelRepository.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CodeSnippets.Shared;
using CodeSnippets.Shared.Domain;

namespace CodeSnippets.Domain
{
    public class ModelRepository
    {
        private readonly List<ModelValidation> _modelValidations;
        private readonly IRepository<Fund> _fundRepository;
        private readonly IRepository<Investment> _investmentRepository;

        public ModelRepository()
        {
            _fundRepository = new FundRepository();
            _investmentRepository = new InvestmentRepository();
            _modelValidations = new List<ModelValidation>();
        }

        public IList<Model> Load(string filePath)
        {
            var models = new List<Model>();
            try
            {
                int rowIndex = 0;
                using (var readFile = new StreamReader(filePath))
                {
                    string line;
                    while ((line = readFile.ReadLine()) != null)
                    {
                        string[] row = line.Split(',');
                        if (rowIndex != 0)
                        {
                            var model = new Model
                            {
                                Name = row[0],
                                Description = row[1],
                                InvestmentCode = row[2],
                                FxRate = Convert.ToDouble(row[3]),
                                DailyPnl = Convert.ToDouble(row[4])
                            };
                            models.Add(model);
                        }
                        rowIndex++;
                    }
                }
            }
            catch (Exception e)
            {
                string logMessage = "ModelRepository > Load " + "[" + e.StackTrace + "]";
                ApplicationLogger.Instance.Log(typeof(ModelRepository),  logMessage, LogLevel.Error);
            }
            return models;
        }

        public IList<ModelTransaction> Transform(IList<Model> models)
        {
            return models.Select(model => new ModelTransaction
            {
                Name = model.Name,
                Description = model.Description,
                InvestmentCode = model.InvestmentCode,
                FxRate = model.FxRate,
                DailyPnl = model.DailyPnl
            }).ToList();
        }

        public IList<ModelTransaction> Compute(IList<ModelTransaction> modelTransactions)
        {
            foreach (var modelTransaction in modelTransactions)
                modelTransaction.RepPnl = modelTransaction.FxRate*modelTransaction.DailyPnl;
            return modelTransactions;
        }

        public void Enrich(IList<ModelTransaction> modelTransactions)
        {
            List<Fund> funds = _fundRepository.GetAll().ToList();
            List<Investment> investments = _investmentRepository.GetAll().ToList();
            var enrichQuery = (from i in investments
                               join f in funds on i.FundId equals f.Id
            select new { FundName = f.Name, FundID = f.Id, InvestmentCode = i.Code, InvestmentId = i.Id, InvestmentName = i.Name });
            foreach (var modelTransaction in modelTransactions)
            {
                var fundQuery = enrichQuery.FirstOrDefault(e => e.InvestmentCode == modelTransaction.InvestmentCode);
                modelTransaction.FundId = (fundQuery == null) ? -1 : fundQuery.FundID;
                var investmentQuery = enrichQuery.FirstOrDefault(e => e.InvestmentCode == modelTransaction.InvestmentCode);
                modelTransaction.InvestmentId = (investmentQuery == null) ? -1 : investmentQuery.InvestmentId;
            }
        }

        public void Validate(IList<ModelTransaction> modelTransactions)
        {
            throw new NotImplementedException();
        }

        public void Persist(IList<ModelTransaction> modelTransactions)
        {
            throw new NotImplementedException();
        }
    }
}
--
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <appSettings>
    <add key="feedLocation" value="C:\Data\Professional\TechnologySkills\Software Engg Principles\SourceCode\MultiThreading\ThreadPool\QueueWorkUserItem\Feeds" />
  </appSettings>
  <log4net>
    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="C:\Data\Professional\TechnologySkills\Software Engg Principles\SourceCode\MultiThreading\ThreadPool\QueueWorkUserItem\Logs\MDT.UnitTests.log" />
      <param name="AppendToFile" value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="2" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern"
             value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
        <conversionPattern value="%date %logger  >> %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ALL" />
      <appender-ref ref="LogFileAppender" />
    </root>
  </log4net>
</configuration>

--InvestmentRepository
 public IEnumerable<Investment> GetAll()
        {
            return new List<Investment>
            {
                new Investment(){ Name = "MS Boston", Code = "MSB", Id=1, FundId = 1},
                new Investment(){ Name = "MS Woodbarn", Code = "MSW", Id=2, FundId = 1 },
                new Investment(){ Name = "MS Cash Eq", Id=3, Code = "MCE", FundId = 2 },
                new Investment(){ Name = "MS Cash Eq1", Id=4, Code = "MCE1", FundId = 2 },
                new Investment(){ Name = "MS Cash Eq2", Id=5, Code = "MCE2", FundId = 2 },
                new Investment(){ Name = "MS Comm", Id=6, Code = "MSCOM", FundId = 3 }
            };
        }

--FundRepositoy
        public IEnumerable<Fund> GetAll()
        {
            return new List<Fund>
            {
                new Fund(){ Name = "MS REF 1", Code = "MSR1",  Id=1 },
                new Fund(){ Name = "MS REF 2", Code = "MSR2", Id=2 },
                new Fund(){ Name = "MS REF 3", Code = "MSR#", Id=3 }
            };
        }
---Feeds
Name,Description,InvestmentCode, FXRate,DailyPnl
MCE2 test,MCE2 test DESCR,MCE2,1.0,4575
MSCOM test,MSCOM test DESCR,MSCOM,2,357
MCE test,MCE test DESCR,MCE,.6,34
MCE1 test,MCE1 test DESCR,MCE1, 2.5, 1000
MSE test,MSE test DESCR,MSE,3,489
TSE test,TSE test DESCR,TSE,4,900
MSB Test1,MSB Test1 DESCR,MSB, 2.4,12
MSW test,MSW test DESCR,MSW, 3.4,200
MCE test,MCE test DESCR,MCE, 5.6, 34
MCE1 test,MCE1 test DESCR,MCE1, 3.2,1000

   WorkUnitManager workUnitManager = new WorkUnitManager();
            IList<WorkUnit> workUnits = workUnitManager.GenerateWorkUnits();
            foreach (var workUnit in workUnits)
            {
                Console.WriteLine(" Work Unit {0}  ", workUnit.Code);
            }
            workUnitManager.Process(workUnits);

Thursday, July 24, 2014

Multi -threading Querirs

Difference between ManaulResetEvent and AutoResetEvent 


  • Difference between a tollbooth and a door. The ManualResetEvent is the door, which needs to be closed (reset)
  • AutoResetEvent executes WaitOne() and Reset() as a single atomic operation..
  • An AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).
Exception Handling across several threads
http://www.codeproject.com/Articles/152765/Task-Parallel-Library-of-n

http://www.yoda.arachsys.com/csharp/threads/threadpool.shtml

Tuesday, July 22, 2014

Code Quirks

Can Func's point to instance methods ?
Whats the difference between Func and Delegates ?
Difference between lock and Thread.QueueWorkUserItem
Can delegates point to instance methods ?

-----
using System;
using System.Collections.Generic;
using System.Linq;

namespace LinqExamples
{
    #region Data

    class Product
    {
        public string Name { get; set; }
        public int CategoryID { get; set; }
    }

    class Category
    {
        public string Name { get; set; }
        public int ID { get; set; }
    }

    public class Student
    {
        public string Name { get; set; }
        public string Standard { get; set; }
        public string Status { get; set; }

        public Student(string name, string standard, string status)
        {
            this.Name = name;
            this.Standard = standard;
            this.Status = status;
        }
    }
    #endregion

    class Program
    {
        static void Main(string[] args)
        {
            /*
            var users = new List<User>
            {
                new User{Id = 1, FirstName = "Sam"},
                new User{Id = 2, FirstName = "Dave"},
                new User{Id = 3, FirstName = "Julia"}
            };

            var groups = new List<Group>
            {
                new Group{Id = 1, Name = "NJHawks"},
                new Group{Id = 2, Name = "NYJets"}
            };

            var userGroups = new List<UserGroup>
            {
                new UserGroup{UserId = 1, GroupId=1},
                new UserGroup{UserId = 1, GroupId=2},
                new UserGroup{UserId = 2, GroupId=2},
                new UserGroup{UserId = 3, GroupId=1},
                new UserGroup{UserId = 3, GroupId=2}
            };


            var innerJoinQuery = from u in users
                                 join ug in userGroups on u.Id equals ug.UserId
                                 join g in groups on ug.GroupId equals g.Id
                                 where u.FirstName == "Sam"
                                 select new {UserId = u.Id, u.FirstName, GroupName = g.Name};

         
          foreach (var item in innerJoinQuery)
           {
               Console.WriteLine("FirstName : {0} ,UserId : {1}, GroupId : {2} ", item.UserId,  item.FirstName,  item.GroupName);
           }

            */

            //Updating Linq Objects
            /*var arrStudents = new Student[]
                                    {
                                        new Student("AAA","1","A"),
                                        new Student("BBB","2","B"),
                                        new Student("CCC","3","C"),
                                        new Student("DDD","4","D"),
                                        new Student("EEE","5","E"),
                                        new Student("FFF","6","F"),
                                        new Student("GGG","7","G"),
                                        new Student("HHH","8","H"),
                                        new Student("III","9","I")
                                    };

            Console.WriteLine("Before update");
            foreach (Student student in arrStudents)
            {
                Console.WriteLine(String.Format("{0},{1},{2}", student.Name, student.Standard, student.Status));
            }

            var query = (from stud in arrStudents
                         where stud.Name == "BBB"
                         select stud)
                        .Update(st => { st.Standard = "0"; st.Status = "X"; });

            Console.WriteLine("After update");
            foreach (Student _student in arrStudents)
            {
                Console.WriteLine(String.Format("{0},{1},{2}", _student.Name, _student.Standard, _student.Status));
            }*/

            /*Update Collections */
            /*Create data repository*/
            var fundFamilies = new List<FundFamily>
                                   {
                                       new FundFamily {Id = 1, Code = "RE"},
                                       new FundFamily {Id = 2, Code = "NON-RE"},
                                       new FundFamily {Id = 3, Code = "PEQ"}
                                   };

            var funds = new List<Fund>
                            {
                                new Fund {Id = 1, Code = "MSREF1", FundFamilyId = 1},
                                new Fund {Id = 2, Code = "MSREF2", FundFamilyId = 1},
                                new Fund {Id = 3, Code = "EQ1", FundFamilyId = 2}
                            };
            var modelDatas = new List<ModelData>
                                 {
                                     new ModelData()
                                         {ModelCode = "BSP", ModelName = "Boston Seaport", FundCode = "MSREF1"},
                                     new ModelData()
                                         {ModelCode = "WBS", ModelName = "Woodbrook Sea", FundCode = "MSREF1"},
                                     new ModelData()
                                         {ModelCode = "EQTL", ModelName = "Private Tryport", FundCode = "EQ1"},
                                     new ModelData()
                                         {ModelCode = "EQTL1", ModelName = "Private Tryport2", FundCode = "EQ1"}
                                 };

            var query = from f in funds
                        join ff in fundFamilies on f.FundFamilyId equals ff.Id
                        select new {FundFamilyId = ff.Id, FundFamilyCode = ff.Code, Fundid = f.Id, FundCode = f.Code};
            //foreach (var bp in query)
            //    Console.WriteLine("Funds info  - {0}, {1}, {2}, {3}", bp.FundFamilyId, bp.FundFamilyCode, bp.Fundid, bp.FundCode) ;

            //Create ModelTransaction
            var modelTransactions = new List<ModelTransaction>
                                        {
                                            new ModelTransaction()
                                                {ModelCode = "BSP", ModelName = "Boston Seaport", FundCode = "MSREF1"},
                                            new ModelTransaction()
                                                {ModelCode = "WBS", ModelName = "Woodbrook Sea", FundCode = "MSREF1"},
                                            new ModelTransaction()
                                                {ModelCode = "EQTL", ModelName = "Private Tryport", FundCode = "EQ1"},
                                            new ModelTransaction()
                                                {ModelCode = "EQTL1", ModelName = "Private Tryport2", FundCode = "EQ1"}
                                        };


            Console.WriteLine("--Before  Update----");
            foreach (ModelTransaction modelTransaction in modelTransactions)
                Console.WriteLine("Funds info  - {0}, {1}, {2}, {3}", modelTransaction.FundFamilyId,
                                  modelTransaction.FundCode, modelTransaction.FundId, modelTransaction.FundFamilyId);

            Console.WriteLine("--After Update----");
            var metaDataQuery = (from f in funds
                                 join ff in fundFamilies on f.FundFamilyId equals ff.Id
                                 select new {FundCode = f.Code, f.FundFamilyId, FundId = f.Id});
            //.Update(mt => { mt.FundFamilyId = 1 ; mt.FundId = 2; });
         
            //var updateModelTransactionsQuery = (
            //                                       from m in modelTransactions
            //                                       join f in funds on m.FundCode equals f.Code
            //                                       join ff in fundFamilies on f.FundFamilyId equals ff.Id
            //                                       select m);
            //foreach (var m in updateModelTransactionsQuery)
            //{

            //}
            foreach (ModelTransaction modelTransaction in modelTransactions)
            {
                int fundId= metaDataQuery.FirstOrDefault(i => i.FundCode == modelTransaction.FundCode).FundId;
                int fundFamilyId= metaDataQuery.FirstOrDefault(i => i.FundCode == modelTransaction.FundCode).FundFamilyId;
                modelTransaction.FundId = fundId;
                modelTransaction.FundFamilyId = fundFamilyId;
            }

             foreach (ModelTransaction modelTransaction in modelTransactions)
                Console.WriteLine("Funds info  - {0}, {1}, {2}, {3}", modelTransaction.FundFamilyId, modelTransaction.FundCode, modelTransaction.FundId, modelTransaction.FundFamilyId);
           
     
            Console.ReadLine();
        }
    }

 
    public static class UpdateExtensions
    {
        public delegate void Func<TArg0>(TArg0 element);

        public static int Update<TSource>(this IEnumerable<TSource> source, Func<TSource> update)
        {
            if (source == null) throw new ArgumentNullException("source");
            if (update == null) throw new ArgumentNullException("update");
            if (typeof(TSource).IsValueType)
                throw new NotSupportedException("value type elements are not supported by update.");

            int count = 0;
            foreach (TSource element in source)
            {
                update(element);
                count++;
            }
            return count;
        }
    }
}