Task Parallel Library (TPL)

Getting Started:

 

 

–>

Advertisements

Variance in Delegates

1.       Delegates
can have Contravariant Parameter Type and covariant return type.

2.       But
this does not mean Contravariance for the actual function that the delegates
are pointing to.

3.       Eg.

    public static void f1(Object o)
        {
            Debug.WriteLine("Called");
        }

        public static void Main(string[] args)
        {
            Action<object> x = f1;
            Action<string> y = x;
            y("test");
        }

Here even though a Delegate for string is referencing
Object delegate (Contravariance), you can  call the underlying function f1 by
passing a subtype of Object only (which is Covariance).

Use of “in”

1.       The
Action used here is actually delegate void CustomAction<in T>(T arg);

2.       But
when u remove in from the decleration, compiler doesn’t allow:
Action<string> y = x;

3.       Note
that the compiler complains about this even for 2.0 or 3.0 framework and on adding
“in”, it works even in 2.0

 

 

 

 

–>

Asybc Base Class Library

Microsoft.Bcl.Async

Aim of this is to provide support for the async/await

keywords for pre-.NET 4.5 platforms, such as .NET 4, Silverlight 4, and Windows
Phone 7.5. Of course, this includes support for portable class libraries as
well.

1.       http://www.nuget.org/packages/Microsoft.Bcl.Async

2.       http://www.nuget.org/packages/Microsoft.CompilerServices.AsyncTargetingPack

3.       http://blogs.msdn.com/b/bclteam/archive/2013/04/17/microsoft-bcl-async-is-now-stable.aspx

4.       http://www.scottlogic.com/blog/2012/11/07/async-where-can-i-use-it.html

To-Do

1.
http://msdn.microsoft.com/en-us/magazine/jj133817.aspx

 

 

–>

Lambda Expression

1.       It
is a function internally

2.       It
can close on Local Variables

3.       It
uses the latest value of closed vars

int factor = 2;

Func<int,
int> multiplier = n => n * factor;

factor = 10;

Console.WriteLine
(multiplier (3)); // 30

Lambda expressions can themselves
update captured variables:

int seed = 0;

Func<int>
natural = () => seed++;

Console.WriteLine
(natural()); // 0

Console.WriteLine
(natural()); // 1

Console.WriteLine (seed);
// 2

4.       When
returned, It actually returns a Delegate (Note that Func<int> is
the Return Type of Natural() below
)

Eg.

         private static Func<int> Natural()

        {

            int seed = 0;

            return () => seed++; // Returns a closure

        }

 

        private static void Main()

        {

            

            Console.WriteLine((Natural())()); // 0

        }

5.       Note
that 2 instances of the same delegate can be made to reference each other. This
is being done in the eg. Below, where the instance of Func<int> is
returned and is referenced by natural1 and then the same ref. is passed to
natural2

Eg.

         private static Func<int> Natural()
        {
            int seed = 0;
            return () => seed++; // Returns a closure
        }

        private static void Main()
        {
            //var l = new lambda();
            Func<int> natural1 = Natural();
            Func<int> natural2 = natural1;
            Console.WriteLine(natural2()); // 0
            Console.WriteLine(natural2()); // 1
            Console.WriteLine(natural1()); // 2
            Console.WriteLine((Natural())()); // 0
            ////Console.WriteLine(() => "test");
        }

6.       Capturing
is internally implemented by “hoisting” the captured variables into fields of a
private class. When the method is called, via the delegate, the class instance
is created and its lifetime is bound to the delegate instance.

7.       Caveat:
When we capture the iteration variable of a for loop {i}, C# hoists the var outside
the loop. This means that the same variable is then captured for each
iteration, and its val is the last value. This problem was there for foreach as
well in 4.0, but in c# 5.0, its been fixed for foreach loop. Anony. Fn() have
the exact same behavior…

8.       Always
use Lambda in place of anonymous fn(), as internally lamba is that only, but
has more features. Also, for writing  an anonymous method, we need to include
the delegate keyword followed by a parameter declaration and then a method
body.

Eg. delegate (int x) {return x *
x;}
;
vs
x
=> x * x
;

9.
Only extra feature is in anony, you can skip the parameter declaration entirely and
write: delegate { }

 

 

 

–>

C# NotePad


·
C# 3.0 Refresher

o
Automatic Properties

o
Object Initializers

o
Collection Initializers

o
Extension Methods

o
Anonymous Functions

o
Anonymous Methods

o
Lambda Expressions

·
Visual Studio 2010/2012 New
Features

o
Architecture explorer

o
Dependency graphs

o
Sequence diagram

o
Intellitrace

o
And other new features

·
Managed Extensibility Framework

NOTES

1.       Ildsm

a.       http://ilspy.net/

2.       Ilspy

3.       Reflector.exe
vs ildasm

a.       http://stackoverflow.com/questions/1503943/how-to-decompile-a-dll-file-created-in-vs-net

4.       Static
method vs Extension Method

5.       Anonymous
Function is inline delegate // Func and Action

6.       Lambda
Exp

a.       in C# 3.0 and later, lambda expressions supersede anonymous
methods as the preferred way to write inline code

b.      Anonymous methods enable you to omit the parameter list. This
means that an anonymous method can be converted to delegates with a variety of
signatures. This is not possible with lambda expressions.

c.      

7.       LINQ: 3
ways of using LINQ:

a.       Use
enumerable.where, enu.select etc. ie Lambda Expression, using static method
directly

b.      Enu.sel(Enu.where
(NESTING)

c.       Enu.where.select…
(CHAINING)

d.      Using
linq keywords

8.       LINQ
gets executed whenever used (deferred ex) and every time it is used,
irrespective of change in parameters. The latter behavior can be overridden by
converting the query result toList etc. and then use that for further execution

9.       LINQ
is slower than for and foreach, but useful when using with parallel programming
(asParallel())

10.   http://www.linqpad.net/

11.   Powerpoint
Storyboarding for Prototyping(http://tfs.visualstudio.com/en-us/learn/storyboard-your-ideas.aspx
) comes with VS premium and up : http://msdn.microsoft.com/en-us/library/vstudio/hh409276.aspx

12.   Sequence Dia for any
method BEST

13.   2013 Code Map

14.   Architecture tools for
Ultimate Version to create UML, flow etc.

15.   VS 2012 code snippet
manager

16.   Intellitrace vs and
standalone but can’t debug using windbg or debugDiag

17.   Webmatrix for quick creation
of sites etc. http://www.microsoft.com/web/webmatrix/

18.   Snippet designer
extension: http://snippetdesigner.codeplex.com/wikipage?title=createFromScratch&referringTitle=Documentation

19.   http://stackoverflow.com/questions/100420/hidden-features-of-visual-studio-2005-2010

20.    Alt+Shift+F11 for Visual Studio keyboard
scheme
for highlighting word wherever its used in file. Better is http://visualstudiogallery.msdn.microsoft.com/8ffec54d-4e18-4c42-ad33-2ea6f28de464

21.   Pin data
tips

22.   Code Clone analysis in
VS 2012 ultimate to show duplicate code

23.   F1 to see docs of
anything from VS2010

24.   FxCop : FxCop analyzes the compiled object code, not
the original
source code. It
uses
CIL parsing, and callgraph analysis
to inspect assemblies for more than 200 different possible coding standards
violations

25.   StyleCop is
an
open source static
code analysis
 tool from Microsoft that
checks
C# code for conformance to StyleCop’s recommended
coding styles and a subset of Microsoft’s .NET Framework Design Guidelines.
StyleCop analyzes the
source code,
allowing it to enforce a different set of rules from
FxCop (which,
instead of source code, checks
.NET managed code assemblies).

26.   Code analysis in VS
2012 (set its rules from solution properties)

27.   Code Metrix in VS 2012

28.   Lightswitch (for
datacentric apps) vs webmatrix (for cms solutions)

29.   How to use lightswitch
with webmatrix

30.   MEF: there are
2 ways of adding extensions to the source

a.
var a = new AssemblyCatalog(Assembly.GetExecutingAssembly());


var container = new CompositionContainer(a);

 

b.  var container = new CompositionContainer();
             var batch = new CompositionBatch();
             batch.AddPart(new CustomExtensionV1()); batch.AddPart(this);
             container.Compose(batch); 

c.       Apart
from this, every MEF needs the source to mark some properties to be importable
by using [Import]:

[Import(typeof(ICustomDataSource))]

public ICustomDataSource DataSource { get; set; }

a.       And
lastly there should be properties that the Extensions Export,using [Export],
which will replace the source properties:

[Export]

public ICustomDataSource WriteToConsole

           These 4 things are basic to every MEF
implementation. A good eg. Of this is Visual Studio, which exposes properties
as [Import] so that other extensions can then replace those with their own
values and Just Work…without the VS Source Code changing

31.   http://msdn.microsoft.com/en-us/library/dn170416.aspx

32.   http://msdn.microsoft.com/en-us/library/vstudio/bb397687.aspx

33.   http://msdn.microsoft.com/en-us/library/vstudio/bb397951.aspx

34.   A function can be
written as anonymous fn, or del

PARALLELISM

1.       Cancellationtokensource|:
http://msdn.microsoft.com/en-us/library/vstudio/system.threading.cancellationtokensource(v=vs.100).aspx

2.       Map
parallel task window tasks to threads window threads

3.       Parallel.ForEach()

4.       Exception
with Tasks: http://msdn.microsoft.com/en-us/library/dd537614.aspx

5.       Generics
in Tasks

6.      

PERFORMANCE

1.       Windows
Performance Monitor
: perfmon

2.       http://bcl.codeplex.com/wikipage?title=PerfMonitor

1.       Cmd
line tool

2.       perfMonitor
runAnalyse abc.exe

3.       Generates
report

3.       Windows
Performance Analyser

4.       Windows
Performance Recorder or xPerf or perfMonitor to generate etl files to generate
files and then view using Windows Performance Analyser

5.        All
above is for Historical Performance but for live, use perfMon.

6.       perfView

35.   Dispacher…

a.       Win
8 has ui, worker and composition thread

36.   Code Contracts

37.   New Type Lazy

38.   Inter Process
Communication using MemoryMappedFile is new in 4.0 createNew to create a
inmemory file and openExisting to read from that file

39.  

7.     Automatic
Properties

 

1.
Need: Properties can have code put into them without breaking
contract, fields can’t have code put into them without changing them to
properties (and breaking the interface). Properties can be read only or write
only, fields can’t. Properties can be data bound, fields can’t.

 

2.  publicstringForename{ get;set;} 
is same as:
privatestring forename;

 

public

stringForename

 

{

 

    get
    

{

        return

this.forename;

 

    }

 

    set

 

    {

 

        this

.forename = value;

 

    }

 

}

3.       They are
implemented differently in the resulting IL code (and machine language). An
Automatic property is still exposed as a public getter and setter, whereas a
public field is just that – a single field..

4.
implementing an auto property allows you at some
later date to change the internal behavior of either the getter or setter (like
adding a validator) without recompiling or recoding any dependant classes that
use it

5.
read: http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html

6.
see: http://csharp-video-tutorials.blogspot.in/2012/06/part-26-c-tutorial-why-properties.html

7.
Inheritance and props: http://msdn.microsoft.com/en-us/library/75e8y5dd.aspx

 

 

 

 

 

 

 

 

 

 

 

8.
Object
Initializers

9.
Collection
Initializers

10.
Extension
Methods

11.
Anonymous
Functions

12.
Anonymous
Methods

13.
Lambda
Expressions

14.  

 

 

–>

System.DirectoryServices;

using System.DirectoryServices;


ref:

 

  1. Using System.DirectoryServices

 

From <http://msdn.microsoft.com/en-us/library/ms180832(v=vs.80).aspx>

 

  1. System.DirectoryServices Namespace

 

From <http://msdn.microsoft.com/en-us/library/system.directoryservices.aspx>

 

  1. Using System.DirectoryServices to Search the Active Directory

 

From <http://msdn.microsoft.com/en-us/library/ms973834.aspx>

 

  1. Using System.DirectoryServices.AccountManagement

 

From <http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement>

Manually Parsing and Mapping XML in c#

Reading XML in c#

1.  using System.Xml;
2.   XmlReaderSettings settings = new XmlReaderSettings();
3.              settings.IgnoreWhitespace = true;
4.              XmlTextReader textReader = new XmlTextReader(stream);
5.              XmlReader reader = XmlReader.Create(textReader, settings);
 
 
 
Parsing through the tags:
 while (reader.Read())                                     
                    reader.Read();   //Reads A
                    while (!((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "A")))          //till all B End
                    {
                              reader.Read();  //Reads B1
 if (reader.Name == "B1")
                            {
                                 
                                if (reader.HasAttributes)
                                {

                                    if (reader["Ba1"] != null && reader["Ba2"] != null)
                                    {}
                                   reader.Read();
                                while (!((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "B1")))          //till all B End                       
                                { if (reader.Name == "R")
                                        {
                                            if (reader.HasAttributes)
                                            {
                                                String kName = reader["R1"];}
                                            if (kName == null)
                                                {
                                                    reader.MoveToElement();
                                                    reader.Read();
                                                    while (!((reader.NodeType == XmlNodeType.EndElement) && (reader.Name == "p")))
                                                    {
                                                        reader.Read();
                                                    }
                                                    reader.Read();   // to read /p
                                                    reader.Read();      // to read /R
                                                    

                                                }
 
Now to map all the stuff read from the XML file into a custom class’s instance, use:
 
  pCheck = (MyClass)Activator.CreateInstance(AppDomain.CurrentDomain, GroupAssembly (read this also from XML in case it is not the current assembly), ClassName(Read the from the XML as well), trueBindingFlags.Default, nullnew object[] {argument1, argument2}, nullnullnull).Unwrap();
 
 
 THIS IS THE SAMPLE XML:

<!–?xml version=”1.0″ encoding=”utf-8″ ?>
<A>
<B1 Ba1=”sfdsf” Ba2=”sdf”>
<R R1=”sd”>
<p>

 
 
 
 

–>