Thursday, August 8, 2013

ASP.Net, C# new feature note

When I was reading, I came across few new things in asp.net 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.

ASP.net 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);

NOte:
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?

NOte:
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.

Structs
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:

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

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

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

protected
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)

Delegates
      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 (http://msdn.microsoft.com/en-us/library/ff649690.aspx)


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.