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/