Thursday, August 8, 2013

ASP.Net, C# new feature note

When I was reading, I came across few new things in and C# and also some topics which i always keep forgetting. I tried to make some small note of all those topics so next time no need to read everything in detail. Mostly I refer MSDN for these topics, I've attached url also for few.

Redirect to another page

Response.Redirect: requires round trip. It send message to browser to to send new request. It is a GET request from browser.
Server.Transfer() : Faster then Response.Redirect. It transfers the execution of one page to another.
It does not change url in to browser if transferred.
Unable to Transfer page of different Application or non .net Application.
CrossPagePosting: It post page to another page by copying viewstate and content of another controls. Whichever control implements IButtonControl interface can set cross page posting. 
 - Target page can access properties of previous page using "PreviousPage" property.
 - It post one page content to another via Http Post method same like we did in classic ASP.
 - Server.Transfer is server based operation whether cross Page posting is client base posting.

Response.RedirectPermanent(): it is same as response.redirect() but instead of using HTTP status 302 it uses HTTP status 301. It is important for search engine. it’s important for search engines. If a search engine’s web crawler is exploring your website and it receives the 301 status code, it will update the search catalog with the new URL
information. HTTP Handler and Module:
HTTP modules differ from HTTP handlers. An HTTP handler returns a response to a request that is identified by a file name extension or family of file name extensions. 
In contrast, an HTTP module is invoked for all requests and responses. It subscribes to event notifications in the request pipeline and lets you run code in registered event handlers. The tasks that a module is used for are general to an application and to all requests for resources in the application

Named arguments (C# 4.0)
Rather than identifying an argument by position, you can identify an argument by
name. For example:

void Foo (int x, int y) { Console.WriteLine (x + ", " + y); }

void Test()
   Foo (x:1, y:2); // 1, 2

Named arguments can occur in any order. The following calls to Foo are semantically identical:

Foo (x:1, y:2);
Foo (y:2, x:1);

A subtle difference is that argument expressions are evaluated
in the order in which they appear at the calling site. In general,
this makes a difference only with interdependent side-effecting
expressions such as the following, which writes 0, 1:

int a = 0;
Foo (y: ++a, x: --a); // ++a is evaluated first

Of course, you would almost certainly avoid writing such code
in practice!

You can mix named and positional parameters:

Foo (1, y:2);

However, there is a restriction: positional parameters must come before named arguments.

So we couldn’t call Foo like this:
Foo (x:1, 2); // Compile-time error

Named arguments are particularly useful in conjunction with optional parameters.
For instance, consider the following method:

void Bar (int a = 0, int b = 0, int c = 0, int d = 0) { ... }

We can call this supplying only a value for d as follows:

Bar (d:3);
This is particularly useful when calling COM APIs

The 'as' operator
The as operator performs a downcast that evaluates to null (rather than throwing
an exception) if the downcast fails:

Asset a = new Asset();
Stock s = a as Stock; // s is null; no exception thrown

This is useful when you’re going to subsequently test whether the result is null:

if (s != null) Console.WriteLine (s.SharesOwned);

Without such a test, a cast is advantageous, because if it fails, a
more descriptive exception is thrown. We can illustrate by comparing
the following two lines of code:

int shares = ((Stock)a).SharesOwned; // Approach #1
int shares = (a as Stock).SharesOwned; // Approach #2

If a is not a Stock, the first line throws an InvalidCastException, which is an accurate description of what went wrong. The
second line throws a NullReferenceException, which is ambiguous.
Was a not a Stock or was a null?

The as operator cannot perform custom conversions and it cannot do numeric conversions:

long x = 3 as long; // Compile-time error

The as and cast operators will also perform upcasts, although this is not terribly useful because an implicit conversion will do the job.

The 'is' operator
The is operator tests whether a reference conversion would succeed; in other words, whether an object derives from a specified class (or implements an interface). It is often used to test before down casting.

if (a is Stock)
Console.WriteLine (((Stock)a).SharesOwned);

The is operator does not consider custom or numeric conversions, but it does consider unboxing conversions

'new' Keyword
Occasionally, you want to hide a member deliberately, in which case you can apply
the 'new' modifier to the member in the subclass. The new modifier does nothing more than suppress the compiler warning that would otherwise result:

public class A { public int Counter = 1; }
public class B : A { public new int Counter = 2; }

The new modifier communicates your intent to the compiler—and other
programmers—that the duplicate member is not an accident. C# overloads the new keyword to have independent meanings in different contexts. Specifically, the new operator is different from the new member modifier.

A struct is similar to a class, with the following key differences:
• A struct is a value type, whereas a class is a reference type.
• A struct does not support inheritance (other than implicitly deriving from
object, or more precisely, System.ValueType).
A struct can have all the members a class can, except the following:
• A parameter less constructor
• A finalizer
• Virtual members

A struct is used instead of a class when value-type semantics are desirable. Good
examples of structs are numeric types, where it is more natural for assignment to
copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiate of an object on the heap; this incurs a useful savings when creating many instances of a type. For instance, creating an array of value type requires only a single heap allocation.

Access Modifiers
To promote encapsulation, a type or type member may limit its accessibility to other types and other assemblies by adding one of five access modifiers to the declaration:

Fully accessible; the implicit accessibility for members of an enum or interface

Accessible only within containing assembly or friend assemblies; the default
accessibility for non-nested types

Visible only within containing type; the default accessibility members of a class
or struct

Visible only within containing type or sub classes

protected internal
The union of protected and internal accessibility (this is less restrictive than
protected or internal alone)

      A delegate dynamically wires up a method caller to its target method. The caller invokes the delegate, and then the delegate calls the target method. This indirection decouples the caller from the target method.

-Multicast delegate : Delegate can reference list of target methods. + and += operator combines delegate 
instance. -= will remove delegate instance.

- Delegates are immutable, so when you call += or -=, you’re in fact creating a new delegate instance and assigning it to the existing variable.

-When a delegate object is assigned to an instance method, the delegate object must maintain a reference not only to the method, but also to the instance to which the method belongs. The System.Delegate class’s Target property represents this instance (and will be null for a delegate referencing a static method).

Yield Statement
while iteration On "yield  return" statement control is returned to caller, but calle's state is maintained so that method can continue execution as soon as callers enumerates the next element. Lifetime of  this state of calle's bound to enumerator  such that the state can be released when the caller  has finished enumerating.

using System;
using System.Collections.Generic;

class Test
        static void Main()
            foreach (int fib in Fibs(6))
                Console.Write(fib + " ");
        static IEnumerable<int> Fibs(int fibCount)
            for (int i = 0, prevFib = 1, curFib = 1; i < fibCount; i++)
                yield return prevFib;
                int newFib = prevFib + curFib;
                prevFib = curFib;
                curFib = newFib;


OUTPUT: 1 1 2 3 5 8
The compiler converts iterator methods into private classes that implement IEnumerable<T> and/or IEnumerator<T>. The logic within the iterator block is “inverted” and spliced into the MoveNext method and Current property on the compiler-written enumerator class. This means that when you call an iterator
method, all you’re doing is instantiating the compiler-written class; none of your code actually runs! Your code runs only when you start enumerating over the resultant sequence, typically with a foreach statement.

yield break
The yield break statement indicates that the iterator block should exit early, without returning more elements. We can modify Foo as follows to demonstrate:

static IEnumerable<string> Foo (bool breakEarly)
    yield return "One";
    yield return "Two";
    if (breakEarly)
      yield break;
    yield return "Three";

- A yield return statement cannot appear in a try block that has a catch clause:

- Composing Sequences (check C# 4.0 Nutshell 4th edition page 167 )

Null Coalescing Operator ??
- Can be used with Nullable and Reference type.
- If oprand is not null then it takes value and assigned otherwise it assin default value.

int? x = null;
int y = x ?? 5; // y is 5
int? a = null, b = 1, c = 2;
Console.WriteLine (a ?? b ?? c); // 1 (first non-null value)

- This frequently occurs in database programming, where a class is mapped to a table with nullable columns.

MVP and MVC Pattern

The MVP pattern is a UI presentation pattern based on the concepts of the MVC pattern. The pattern separates responsibilities across four components: the view is responsible for rending UI elements, the view interface is used to loosely couple the presenter from its view, the presenter is responsible for interacting between the view/model, and the model is responsible for business behaviors and state management. In some implementations the presenter interacts with a service (controller) layer to retrieve/persist the model. The view interface and service layer are commonly used to make writing unit tests for the presenter and the model easier.

Key Benefits

Before using any pattern a developers needs to consider the pros and cons of 
using it. There are a number of key benefits to using either the MVC or MVP pattern (See list below). But, there also a few draw backs to consider. The biggest drawbacks are additional complexity and learning curve. While the patterns may not be appropriate for simple solutions; advance solutions can greatly benefit from using the pattern. I’m my experience a have seen a few solutions eliminate a large amount of complexity but being re-factored to use either pattern.

Loose coupling – 
      The presenter/controller are an intermediary between the UI code and the model. This allows the view and the model to evolve independently of each other.

Clear separation of concerns/responsibility
    o    UI (Form or Page) – Responsible for rending UI elements
    o    Presenter/controller – Responsible for reacting to UI events and interacts with the model
    o    Model – Responsible for business behaviors and state management

Test Driven – By isolating each major component (UI, Presenter/controller, and model) it is easier to write unit tests. This is especially true when using the MVP pattern which only interacts with the view using an interface.

Code Reuse – By using a separation of concerns/responsible design approach you will increase code reuse. This is especially true when using a full blown domain model and keeping all the business/state management logic where it belongs.

Hide Data Access – Using these patterns forces you to put the data access code where it belongs in a data access layer. There a number of other patterns that typical works with the MVP/MVC pattern for data access. Two of the most common ones are repository and unit of work. (See Martin Fowler – Patterns of Enterprise Application Architecture for more details)

Flexibility/Adaptable – By isolating most of your code into the presenter/controller and model components your code base is more adaptable to change. For example consider how much UI and data access technologies have changed over the years and the number of choices we have available today. A properly design solution using MVC or MVP can support multi UI and data access technologies at the same time.

Key Differences:
So what really are the differences between the MVC and MVP pattern. Actually there are not a whole lot of differences between them. Both patterns focus on separating responsibility across multi components and promote loosely coupling the UI (View) from the business layer (Model).  The major differences are how the pattern is implemented and in some advanced scenarios you need both presenters and controllers.

Here are the key differences between the patterns:

MVP Pattern
o    View is more loosely coupled to the model. The presenter is responsible for binding the model to the view.
o    Easier to unit test because interaction with the view is through an interface
o    Usually view to presenter map one to one. Complex views may have multi presenters.

MVC Pattern
o    Controller are based on behaviors and can be shared across views
o    Can be responsible for determining which view to display (Front Controller Pattern)

Repository Pattern.
It is a one layer of abstraction which isolate domain objects from database access code and acting like in memory domain object.  
- It helps where large number of domain classes exists or heavy querying exists. It minimize duplicate query logic.
- Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. 
- Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
- You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
It centralizes the data logic or Web service access logic.
It provides a substitution point for the unit tests.
It provides a flexible architecture that can be adapted as the overall design of the application evolves.
Check for more info (

Unit of work Pattern
This pattern keeps track of everything happened during business transaction that affect to database.
Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problems.
- If you update database for very small changes then it will increase the database call which end up very slow. It also requires you to open transaction  that spans multiple business request.
- A Unit of Work keeps track of everything you do during a business transaction that can affect the database. When you're done, it figures out everything that needs to be done to alter the database as a result of your work.

Data Mapper Pattern: 
A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
- Objects and relational databases have different mechanisms for structuring data. Many parts of an object, such 
as collections and inheritance, aren't present in relational databases. When you build an object model with a lot of business logic it's valuable to use these mechanisms to better organize the data and the behavior that goes with it. Doing so leads to variant schemas; that is, the object schema and the relational schema don't match up.
- The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface 
code, and certainly no knowledge of the database schema.

Tuesday, January 29, 2013

TFS tutorials for beginners

What is TFS?
It is a team foundation server. It is a central repository  or storage with version control. Initially Microsoft has VSS(Visual source safe ) for version control. TFS is new extended version of VSS with lot of new features and capabilities.
Three major features
  •  Source Control
  •  Builds
  • Work Items

We will discuss all of above shortly.    Lets start with connect to TFS server with images.

In order to connect TFS from visual studio. Click on Team menu and click on "Connect to Team Foundation Server.."  You can do it same from Start page also.

It will open following dialog box. Click on "Servers.." button.

You can add your TFS server here by clicking on Add button.

Add TFS server Name. If you have additional path after server then you can add it in Path text box. It will show final TFS url in preview section.

 Once you add url, you will get following like dialog box window, where you can find all team projects. you can select your project by check it and click on "Connect".

After connect it opens Team explorer window in visual studio. Which has sections like  Documents, Reports, Work Items, Builds, Source Control.

Source control opens following like  explorer in visual studio. Select your project folder. that project folder should be mapped with your local machines folder. If it is not mapped then it shows at Local Path section as "Not mapped". Click on "Not mapped" link and you can map TFS folder with local machine folder.

It opens following like window. you can insert your local machine path to  map folder. once you click on "Map" button. It downloads all source code files from TFS server to your local machine mapped folder.

It will show following like explorer after mapping. you can find your .sln (solution) file and directly open from there.

You can see different  symbol for particular files. 
  "+" is for newly added file
            "right mark" for checked out file.
"lock" for checked in file

Add new file

You can add new file from project solution and it will automatically added to TFS and shows as "+" symbol. you also can add existing file to TFS from Source Control explorer by right click and "Add items to folder".

Check out

If you want to change already existing file then you need to checked out it first. It will lock files for other users and available for you in edit mode. checked out file shows in "right mark" symbol.

Check in

After finished working on file you can commit your changes back to TFS by check in them.  you can check single file by right click on that file from solution explorer in visual studio and click on "Check in".

You can add your comments like what change you have done etc. on comments box. you can see all related files only has checked for check in following image.

You can also check in multiple file by opening "View Pending changes" window in visual studio. you can select multiple files from there by checked them and check in together. you can also attach "Work Item" for each check in. Check in will create new Change set in TFS. it will be new unique changes set number assigned for each change set. 

Added more info here (