Tuesday, March 30, 2010

Non-Generic Vs. Generic Type

Non-GenericSimilar Generic Type
ArrayListList<T>
HashtableDictionary<TKey,TValue>
SortedListSortedList<TKey,TValue>
QueueQueue<T>
StackStack<T>
IenumerableIEnumerable<T>
ICollectionN/A (use IEnumerable<T>anything that
extends it)
N/AICollection<T>
IlistIList<T>
CollectionBaseCollection<T>
ReadOnlyCollectionBaseReadOnlyCollection<T>
DictionaryBaseN/A (just implement IDictionary<TKey,TValue>
N/ASortedDictionary<TKey,TValue>
N/AKeyedCollection<TKey,TItem>
N/ALinkedList<T>

Wednesday, March 10, 2010

ASP.NET Impersonation

It is an important security feature which have ability to control the identity under which code is executed. Impersonation is when ASP.NET executes code in the context of an authenticated and authorized client. By default, ASP.NET does not use impersonation and instead executes all code using the same user account as the ASP.NET process, which is typically the ASPNET account. This is contrary to the default behavior of ASP, which uses impersonation by default. In Internet Information Services (IIS) 6, the default identity is the NetworkService account.
Impersonation is disabled. This is the default setting. <identity impersonate="false">
Impersonation enabled. In this instance, ASP.NET impersonates the token passed to it by IIS, which is either an authenticated user or the anonymous Internet user account (IUSR_machinename). <identity impersonate="true">
Impersonation enabled for a specific identity. In this instance, ASP.NET impersonates the token generated using an identity specified in the Web.config file. <identity  password="password" impersonate="true" username="domain\user">

Monday, December 7, 2009

Different Type of Reports in SSRS (2008)

  • Ad hoc reports
  • Cached reports
  • Clickthrough reports
  • Drilldown reports
  • Drillthrough reports
  • Linked reports
  • Parameterized reports
  • Snapshot reports
  • Subreports

Wednesday, December 2, 2009

Implementation of two interface having the same method signature in the same class

If the signature of the methods in two different interfaces are same and both the interfaces are going be implemented in the same class. Following is the two interfaces:
public interface Interface1 { string PrintName(); }
public interface Interface2 { string PrintName(); }
From the above code we can infer that we have two interface with names Interface1 and Interface2 and both have a single method named “PrintName”. The signatures of both the methods are same and we need to implement the interfaces in our class “myClass”. One way of implementing the interface is as shown below (just having a “public” implementation of the interface method only once).
public class myClass : Interface1, Interface2
{
public myClass() { }
public string PrintName() { return this.GetType().Name; }
}
The above implementation has got a limitation i.e the method “PrintName” is considered to be a common method for all i.e common method for the class, and for the interfaces Interface1 and Interface2. If you are writing a code shown below
myClass myclass = new myClass ();
Interface1 i1 = new myClass ();
Interface2 i2 = new myClass ();
Console.WriteLine(myclass.PrintName());
Console.WriteLine(i1.PrintName());
Console.WriteLine(i2.PrintName());
All the calls to method “PrintName” will give you the same result, the name of the class i.e. “myClass”. This is because all call to the method goes to the same definition. Now if you want to give different implementation to the methods in interface Interface1 and Interface2; you have two implementations of the same method and prefix the method names with the interface name as shown below.
public class myClass : Interface1, Interface2
{
public myClass() { }
string Interface1.PrintName() { return “Interface1 PrintName Method”; }
string Interface2.PrintName() { return “Interface2 PrintName Method”; }
}
Now the below code will give you different output.
Interface1 i1 = new myClass();
Interface2 i2 = new myClass();
Console.WriteLine(i1.PrintName());// Will print " Interface1 PrintName Method"
Console.WriteLine(i2.PrintName());// Will print " Interface2 PrintName Method"
So this is how two interfaces having the same method signature can be given different implementation in the same class.

Tuesday, December 1, 2009

Life cycle of an object

  1. When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.
  2. If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use and it becomes eligible for destruction.
  3. The C# compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future. For instance, if a local variable that is in scope is the only existing reference to an object, but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure, the garbage collector may (but is not required to) treat the object as no longer in use.
  4. Once the object is eligible for destruction, at some unspecified later time the destructor (if any) for the object is run. Unless overridden by explicit calls, the destructor for the object is run once only.
  5. Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for collection.
  6. Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.
The behavior of the garbage collector can be controlled, to some degree, via static methods on the class System.GC. This class can be used to request a collection to occur, destructors to be run (or not run), and so forth.
Note:
Destructors are not inherited. Thus, a class has no destructors other than the one that may be declared in that class.

Since a destructor is required to have no parameters, it cannot be overloaded, so a class can have, at most, one destructor.
Destructors are invoked automatically, and cannot be invoked explicitly. An instance becomes eligible for destruction when it is no longer possible for any code to use that instance. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.  (http://www.devx.com/dotnet/Article/33167/1954)

Table Variable vs Temporary Table (#, ##)

As temporary tables (#, ##) and table variables. While the differences between ##table (global temporary table) and #table (local temporary table) are well understood, there is a fair amount of confusion between #table and table variable.
The scoping rules of the table variable are similar to any other programming variables. For example, if you define a variable inside a stored procedure, it can’t be accessed outside the stored procedure. Incidentally, #table is very similar. So why did we create table variables? Well, a table variable can be very powerful when used with stored procedures to pass it as input/output parameters (new functionality available starting with SQL Server 2008) or to store the result of a table valued function. Here are some similartities and differences between the two:
  • First, the table variable is NOT necessarily memory resident. Under memory pressure, the pages belonging to a table variable can be pushed out to tempdb.
  • Second, when you create a table variable, it is like a regular DDL operation and its metadata is stored in system catalog.
  • Third, transactional and locking semantics. Table variables don’t participate in transactions or locking.
  • Fourth, the operations done on table variable are not logged.
  • Fifth, no DDL is allowed on table variables. So if you have a large rowset which needs to be queried often, you may want to use #table when possible so that you can create appropriate indexes. You can get around this by creating unique constraints when declaring table variable.
  • Finally, no statistics is maintained on table variable which means that any changes in data impacting table variable will not cause recompilation of queries accessing table variable. 
These are some of the drawbacks of Table Variable as compared to temporary tables:
  • Non-clustered indexes cannot be created on table variables, other than the system indexes that are created for a PRIMARY or UNIQUE constraint. That can influence the query performance when compared to a temporary table with non-clustered indexes.
  • Table variables do not maintain statistics like temporary tables can. Statistics cannot be created on table variables through automatic creation or by using the CREATE STATISTICS statement. Therefore, for complex queries on large tables, the lack of statistics may deter the optimizer to determine the best plan for a query, thus affecting the performance of that query.
  • The table definition cannot be changed after the initial DECLARE statement.
  • Tables variables cannot be used in a INSERT EXEC or SELECT INTO statement.
  • CHECK constraints, DEFAULT values, and computed columns in the table type declaration cannot call user-defined functions.
  • You cannot use the EXEC statement or the sp_executesql stored procedure to run a dynamic SQL Server query that refers a table variable, if the table variable was created outside the EXEC statement or the sp_executesql stored procedure. Because table variables can be referenced in their local scope only, an EXEC statement and a sp_executesql stored procedure would be outside the scope of the table variable. However, you can create the table variable and perform all processing inside the EXEC statement or the sp_executesql stored procedure because then the table variables local scope is in the EXEC statement or the sp_executesql stored procedure.
Table variables have the following advantages over temporary tables:
  • Table variables, such as local variables, have a well defined scope at the end of which they are automatically cleared.
  • Table variables result in fewer recompilations of a stored procedure as compared to temporary tables.
  • Transactions that involve table variables last only for the duration of an update on the table variable. Therefore, table variables require less locking and logging resources. Because table variables have limited scope and are not part of the persistent database, transaction rollbacks do not affect them.

Friday, November 13, 2009

ASP.NET 2.0 AJAX Extensions Update Panel - Nested Update Panel

The thumb rule with nested update panels is as follows:-
Parent Update Panel refreshes all the contents including Child Update Panel's contents even if the Child Update Panel's update mode is set to Conditional; Child Update Panel refreshes only its contents and doesnt refresh that of the Parent Update Panel unless, the update mode for the parent update panel is not set to Conditional;The HTML for the Nested Update Panel is as below:-

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<table width="80%" border="3">
<tr>
<td>
Label outside all the Update Panels
<asp:Label ID="Label3" runat="Server" Font-Bold="true"></asp:Label>
<br />
<br />
<asp:Button ID="Button3" runat="Server" Text="Refresh" />
<br />
<br />
</td>
</tr>
<tr>
<td>
<table width="65%" border="2">
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
Label within the Parent Update Panel
<asp:Label ID="Label1" runat="server" Font-Bold="true"></asp:Label>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Refresh" />
<table width="40%" border="1">
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<br />
<br />
Label within the Child Update Panel
<asp:Label ID="Label2" runat="server" Font-Bold="True"></asp:Label>
<br />
<br />
<asp:Button ID="Button2" runat="server" Text="Refresh" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</form>

Code behind
protected void Page_Load(object sender, EventArgs e){

Label1.Text = System.DateTime.Now.ToString();
Label2.Text = System.DateTime.Now.ToString();
Label3.Text = System.DateTime.Now.ToString(); }
When you run the above page, you will notice that the label outside the Update Panels, the parent update panel contents and the child update panel contents.
When you click on the top most button, it refreshes the whole page and subsequently, all the labels get refreshed with the new date time.
However, when you click on the second refresh button which is marked inside the Parent Update Panel you will notice that the top most label doesnt get refreshed but both the Label 2 and Label 3 gets refreshed, although I have marked UpdateMode as conditional for the Child UpdatePanel. The reason being, the parent updates all the child update panels nested within.
Finally, when you click on the last Refresh button which is marked inside the Child Update Panel, you will notice that only the respective label gets refreshed.
Note that, if I remove the property UpdateMode=Conditional for the UpdatePanel1 (parent), both the labels will get refreshed.

ASP.NET 2.0 AJAX Extensions Update Panel - Multiple Update Panels

One of the main properties of an UpdatePanel is its UpdateMode property. The UpdateMode property is by default set to "Always".
However, when you have more than a single update panel or when you want to control as to when the Update Panel needs to get refresh, then setting the UpdateMode property to "Condition" is the first step.
Let us consider a scenario where we have 3 Update Panels in a page. The HTML for the same is as below:-
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<table width="100%">
<tr>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 1</u></b>
<br /><br />
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" />
<br /><br />
<asp:Button ID="Button1" runat="Server" Text="Refresh" OnClick="Button1_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 2</u></b>
<br /><br />
<asp:Label ID="Label2" runat="server"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" />
<br /><br />
<asp:Button ID="Button2" runat="Server" Text="Refresh" OnClick="Button2_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td style="height: 64px">
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<b><u>Section 3</u></b>
<br /><br />
<asp:Label ID="Label3" runat="server"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server" />
<br /><br />
<asp:Button ID="Button3" runat="Server" Text="Refresh" OnClick="Button3_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>

Note that for all the UpdatePanels, I have set the UpdateMode to conditional. The application logic or codebehind for the above is as follows:-
protected void Page_Load(object sender, EventArgs e){
Label1.Text = System.DateTime.Now.ToString();
Label2.Text = System.DateTime.Now.ToString();
Label3.Text = System.DateTime.Now.ToString(); }
protected void Button1_Click(object sender, EventArgs e) { TextBox2.Text = TextBox1.Text; }
protected void Button2_Click(object sender, EventArgs e){ }
protected void Button3_Click(object sender, EventArgs e){ }
When you run this page, you will notice that there are four Sections - Section 1, 2 & 3. When you click on the Refresh button, the date time value gets refreshed only for the particular section. The other values doesnt get changed.
If you remove the UpdateMode=Conditional from the above UpdatePanel declarations, you will notice that all the labels get refreshed.
Hence, setting the UpdateMode as Conditional is important if you like to control the way the UpdatePanels get refreshed.

Wednesday, November 11, 2009

Singleton Pattern class vs. Static Classes

(1) Static Class cannot be extended whereas singleton pattern class can be extended.
(2) Static Class can still have instances (unwanted instances) whereas singleton pattern class prevents it.
(3) Static Class cannot be initialized with a STATE(parameter), whereas singleton pattern class can.
Note: The difference is in Singleton pattern there is an instance of an object and the object resides in Heap memory area and can be passed in different threads.
But if u make the entire class as static with all static methods there will be no object instance, your entire code will be just loaded in the code section.

Wednesday, October 21, 2009

Static Constructor in C#

C# supports following two types of constructor:
  1. Class constructor (static constructor)
  2. Instance constructor (non-static constructor)
Static constructor is a special type of constructor, introduced with C#. It gets called before the creation of the first object of a class(probably at the time of loading an assembly).
See example below.
public class StaticTestClass1(){
static StaticTestClass1(){
//Static members may be accessed from here
//Code for Initialization}
}
While creating a static constructor, a few things need to be kept in mind:
  •  There is no access modifier require to define a static constructor.
  •  There may be only one static constructor in a class.
  •  The static constructor may not have any parameters.
  •  Static constructor may only access the static members of the class.

Call a server-side method from client-side JavaScript

1. Creating a new ASP.NET project
AJAX is required, thus a new “AJAX enabled ASP.NET Web Application” has to be created on Visual Studio 2005 or “ASP.NET Web Application” on 2008.
2. Modifying the server-side code
Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.Now let’s create a simple function that returns a string value.
[System.Web.Services.WebMethod]
public static string Message() { return "Hello from the server-side World!"; }
3. Modifying the ScriptManager
The “EnablePageMethods” attribute has to be added on the ScriptManager tag.
<'asp:ScriptManager ID'="ScriptManager1" runat="server" EnablePageMethods="true" />
4. Adding a simple HTML button
We are going to add a simple HTML button rather than a server-side ASP.NET button control. The “onClick” event is going to be associated with the JavaScript function “GetMessage”.
<'input' onclick="GetMessage()" type="submit" value="Get Message" />
5. Adding the JavaScript code
Let’s add the “GetMessage” JavaScript function, which is going to call our server-side “Message” method.
function GetMessage() { PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure); }
The “OnGetMessageSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnGetMessageFailure” will be called if an exception is thrown.
So let’s add these two functions:
function OnGetMessageSuccess(result, userContext, methodName) { alert(result); }
function OnGetMessageFailure(error, userContext, methodName) { alert(error.get_message()); }
Please note that you can give to the functions any name you wish, as long as they match the PageMethods call parameters.
If there are no errors, the “OnGetMessageSuccess” will show a pop-up window with our server-side “Message” text. Else, the pop-up will have an exception message.
6. Running the Web Application
This is it, we are ready to run our Web Application. Everything seems to be working just fine on Internet Explorer (IE6 and IE7):
However if we run it on Firefox (currently the latest version is 3.0.4) the pop-up will display the following message:
The server method ‘Message’ failed.
7. Fixing the Firefox issue
We just need to modify the button’s onclick event a bit:
<’input’ type="submit" value="Get Message" onclick="GetMessage();return false;" />
And this would do the trick:
8. Here is the complete source code for your reference
Default.aspx

Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace AJAXEnabledWebApplication2
{
public partial class _Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { }
[System.Web.Services.WebMethod]
public static string Message() { return "Hello from the server-side World!"; }
}
}

Session/State Management


State Management: No web application framework, no matter how advance, can change that HTTP is a stateless protocol. This stateless protocol makes our live easy and inherently we should also forget our users, but unfortunately we cannot. There is a lot at stake if we forget our user.
ASP.Net Framework provides us features by which we can maintain states of your beloved users. We do it by the 2 options provided to us. They are Client Side State Management and Server Side State Management.
There are many techniques that we can apply to management states both at Client or Server sides.
Client Side State Management
• Cookies
• View State
• Hidden Fields
• Control State
• Query String
Server Side State Management
• Session State
• Application State
In this article we will be discussing Session based State Management and how to do InProc, State and SQL Server State Management.
Session:Sessions are stored server side and are unique to every user. Every user accessing the application is given a unique Session Id when the application is first accessed by him or her. For every other request that the user posts to the server, the Session Id is shared by the user and server can recognize who the user is.
In its simplest form, session can be created as
Session[“mySession”] = “some data”;
And can be retrieved as string data = Session[“mySession”].ToString();
Modes of Sessions
In-Process also known as In-Proc
Out-of-Process also known as State Server, SQL Server
In-Process:This model is the fastest, most common and the default behavior of Sessions. Session information is stored inside IIS (Internet Information Service). Please make a note that what ever model you use there will be no change in assigning or retrieving information from sessions. However there few details that you need to look for when working with In-Process Sessions Model:
1. If you change Web.config, Global.asax, application restarts itself and as a result session information is lost.
2. Your information also lost if you change your code files in your App_Code folder.
3. If your IIS restarts, this results in the same.
4. Handy events Session_Start and Session_End in Global.asax file (effective only in In-Process).
5. Web.config file timeout attribute
To configure your application for in-proc session management, the most common and basic set up of your web.config file is in the following manner

Timeout attribute takes numeric values and the unit is Minutes. In this case user’s session will expire in 20 minutes time.
Out-Of-Process:Out-Of-Process State Sessions are stored in a process which runs as a Windows Service called ASP.NET State Service. This service is not running by default and of the many, 2 options to run this service are:
1. Click Start>Run. Type cmd to open Command Prompt. Type net starts aspnet_state. If the service is already not running, this command will start the service.
2. Right click My Computer and select Manage. Expand Services and Application, click Services. In the right panel look for ASP.NET State Service and start by right clicking it and selecting Properties option from the context menu. Select Start up Type as Automatic and start the service by clicking the Start Button.

Dispose and Finalize in C#

Dispose: The following rules outline the usage guidelines for the Dispose method:
  • Implement the dispose design pattern on a type that encapsulates resources that explicitly need to be freed. Users can free external resources by calling the public Dispose method.
  • Implement the dispose design pattern on a base type that commonly has derived types that hold on to resources, even if the base type does not. If the base type has a close method, often this indicates the need to implement Dispose. In such cases, do not implement a Finalize method on the base type. Finalize should be implemented in any derived types that introduce resources that require cleanup.
  • Free any disposable resources a type owns in its Dispose method.
  • After Dispose has been called on an instance, prevent the Finalize method from running by calling the GC.SuppressFinalize Method. The exception to this rule is the rare situation in which work must be done in Finalize that is not covered by Dispose.
  • Call the base class's Dispose method if it implements IDisposable.
  • Do not assume that Dispose will be called. Unmanaged resources owned by a type should also be released in a Finalize method in the event that Dispose is not called.
  • Throw an ObjectDisposedException from instance methods on this type (other than Dispose) when resources are already disposed. This rule does not apply to the Dispose method because it should be callable multiple times without throwing an exception.
  • Propagate the calls to Dispose through the hierarchy of base types. The Dispose method should free all resources held by this object and any object owned by this object. For example, you can create an object like a TextReader that holds onto a Stream and an Encoding, both of which are created by the TextReader without the user's knowledge. Furthermore, both the Stream and the Encoding can acquire external resources. When you call the Dispose method on the TextReader, it should in turn call Dispose on the Stream and the Encoding, causing them to release their external resources.
  • You should consider not allowing an object to be usable after its Dispose method has been called. Recreating an object that has already been disposed is a difficult pattern to implement.
  • Allow a Dispose method to be called more than once without throwing an exception. The method should do nothing after the first call.
  Finalize:The following rules outline the usage guidelines for the Finalize method:
  • Only implement Finalize on objects that require finalization. There are performance costs associated with Finalize methods.
  • If you require a Finalize method, you should consider implementing IDisposable to allow users of your class to avoid the cost of invoking the Finalize method.
  • Do not make the Finalize method more visible. It should be protected, not public.
  • An object's Finalize method should free any external resources that the object owns. Moreover, a Finalize method should release only resources that are held onto by the object. The Finalize method should not reference any other objects.
  • Do not directly call a Finalize method on an object other than the object's base class. This is not a valid operation in the C# programming language.
  • Call the base.Finalize method from an object's Finalize method.
// Design pattern for a base class.
public class Base: IDisposable
{ //Implement IDisposable.
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {// Free other state (managed objects).}
// Free your own state (unmanaged objects).
// Set large fields to null.
}
// Use C# destructor syntax for finalization code.
~Base(){// Simply call Dispose(false).
Dispose (false);
}
// Design pattern for a derived class.
public class Derived: Base{
protected override void Dispose(bool disposing) {
if (disposing) { // Release managed resources. }
// Release unmanaged resources.
// Set large fields to null.
// Call Dispose on your base class.
base.Dispose(disposing); }
// The derived class does not have a Finalize method
// or a Dispose method with parameters because it inherits
// them from the base class.}

Tuesday, September 29, 2009

New features C# 3.0:Lambda Expressions

Lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block. The lambda expression x => x * x is read "x goes to x times x." This expression can be assigned to a delegate type as follows:
delegate int del(int i);
static void Main(string[] args){ del myDelegate = x => x * x; int j = myDelegate(5); //j = 25}
To create an expression tree type:
using System.Linq.Expressions;
namespace ConsoleApplication1
{class Program{
static void Main(string[] args){
Expression< del > myET = x => x * x;} }}
The => operator has the same precedence as assignment (=) and is right-associative.
Lambdas are used in method-based LINQ queries as arguments to standard query operator methods such as Where.
When you use method-based syntax to call the Where method in the Enumerable class (as you do in LINQ to Objects and LINQ to XML) the parameter is a delegate type System..::.Func<(Of <(T, TResult>)>). A lambda expression is the most convenient way to create that delegate. When you call the same method in, for example, the System.Linq..::.Queryable class (as you do in LINQ to SQL) then the parameter type is an System.Linq.Expressions..::.Expression where Func is any Func delegates with up to five input parameters. Again, a lambda expression is just a very concise way to construct that expression tree. The lambdas allow the Where calls to look similar although in fact the type of object created from the lambda is different.
A lambda expression with an expression on the right side is called an expression lambda. Expression lambdas are used extensively in the construction of Expression Trees. An expression lambda returns the result of the expression and takes the following basic form: (input parameters) => expression
The parentheses are optional only if the lambda has one input parameter; otherwise they are required. Two or more input parameters are separated by commas enclosed in parentheses:  (x, y) => x == y
A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces: (input parameters) => {statement;}
delegate void TestDelegate(string s);
TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); }; myDel("Hello");
Lambdas with the Standard Query Operators have an input parameter whose type is one of the Func<(Of <(T, TResult>)>) family of generic delegates. The Func<(Of <(T, TResult>)>) delegates use type parameters to define the number and type of input parameters, and the return type of the delegate. Func delegates are very useful for encapsulating user-defined expressions that are applied to each element in a set of source data. For example, consider the following delegate type:
public delegate TResult Func(TArg0 arg0)
Type Inference in Lambdas When writing lambdas, you often do not have to specify a type for the input parameters because the compiler can infer the type based on the lambda body, the underlying delegate type. For most of the standard query operators, the first input is the type of the elements in the source sequence. So if you are querying an IEnumerable, then the input variable is inferred to be a Customer object, which means you have access to its methods and properties:  customers.Where(c => c.City == "London");
The general rules for lambdas are as follows:
  • The lambda must contain the same number of parameters as the delegate type.
  • Each input parameter in the lambda must be implicitly convertible to its corresponding delegate parameter.
  • The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.
Variable Scope in Lambda Expressions Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the lambda is defined. Variables that are captured in this manner are stored for use in the lambda expression even if variables would otherwise go out of scope and be garbage collected. An outer variable must be definitely assigned before it can be consumed in a lambda expression.
The following rules apply to variable scope in lambda expressions:
  • A variable that is captured will not be garbage-collected until the delegate that references it goes out of scope.
  • Variables introduced within a lambda expression are not visible in the outer method.
  • A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
  • A return statement in a lambda expression does not cause the enclosing method to return.
  • A lambda expression cannot contain a goto statement, break statement, or continue statement whose target is outside the body or in the body of a contained anonymous function.

New features C# 3.0:Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.
The most common extension methods are the LINQ standard query operators that add query functionality to the existing System.Collections..::.IEnumerable and System.Collections.Generic..::.IEnumerable<(Of <(T>)>) types. To use the standard query operators, first bring them into scope with a using System.Linq directive. Then any type that implements IEnumerable<(Of <(T>)>) appears to have instance methods such as GroupBy, OrderBy, Average, and so on. You can see these additional methods in IntelliSense statement completion when you type "dot" after an instance of an IEnumerable<(Of <(T>)>) type such as List<(Of <(T>)>) or Array.
The following example shows how to call the standard query operator OrderBy method on an array of integers. The expression in parentheses is a lambda expression.
class ExtensionMethods2 {
static void Main(){
int[] ints = { 10, 45, 15, 39, 21, 26 };
var result = ints.OrderBy(g => g);
foreach (var i in result)
{System.Console.Write(i + " "); }
} }
//Output: 10 15 21 26 39 45
Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier. Extension methods are only in scope when you explicitly import the namespace into your source code with a using directive.
The following example shows an extension method defined for the System..::.String class. Note that it is defined inside a non-nested, non-generic static class:
namespace ExtensionMethods{
public static class MyExtensions{
public static int WordCount(this String str)
{ return str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries).Length; }
}
The WordCount extension method can be brought into scope with this using directive:
using ExtensionMethods; And it can be called from an application by using this syntax:
string s = "Hello Extension Methods";
int i = s.WordCount();

New features C# 3.0:Object and Collection Initializers

Object initializers let you assign values to any accessible fields or properties of an object at creation time without having to explicitly invoke a constructor. The following example shows how to use an object initializer with a named type.
private class Cat{ // Auto-implemented properties
public int Age { get; set; }
public string Name { get; set; } }
static void MethodA() { // Object initializer
Cat cat = new Cat { Age = 10, Name = "Sylvester" }; }
Object Initializers with anonymous types Although object initializers can be used in any context, they are especially useful in LINQ query expressions. Query expressions make frequent use of anonymous types, which can only be initialized with an object initializer. In the select clause, a query expression can transform objects of the original sequence into objects whose value and shape may differ from the original. This is very useful if you want to store only a part of the information in each object in a sequence. In the following example, assume that a product object (p) contains many fields and methods, and that you are only interested in creating a sequence of objects that contain the product name and the unit price.
var productInfos = from p in products  select new { p.ProductName, p.UnitPrice };
When this query is executed, the productInfos variable will contain a sequence of objects that can be accessed in a foreach statement as shown in this example:  foreach(var p in productInfos){...}
Each object in the new anonymous type has two public properties which receive the same names as the properties or fields in the original object. You can also rename a field when you are creating an anonymous type; the following example renames the UnitPrice field to Price. select new {p.ProductName, Price = p.UnitPrice};
Object initializers with nullable types It is a compile-time error to use a collection initializer with a nullable struct.
Collection Initializers  let you specify one or more element intializers when you initialize a collection class that implements IEnumerable. The element initializers can be a simple value, an expression or an object initializer. By using a collection initializer you do not have to specify multiple calls to the Add method of the class in your source code; the compiler adds the calls. The following examples shows two simple collection initializers:
List digits = new List { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
List digits2 = new List { 0 + 1, 12 % 3, MakeInt() };
The following collection initializer uses object initializers to initialize objects of the Cat class defined in an earlier example. Note that the individual object initializers are enclosed in braces and separated by commas.
List cats = new List{
new Cat(){ Name="Sylvester", Age=8 }, new Cat(){ Name="Whiskers", Age=2}, new Cat() { Name="Sasha", Age=14} };
You can specify null as an element in a collection initializer if the collection's Add method allows it.
List moreCats = new List{
new Cat(){ Name="Furrytail", Age=5 }, new Cat(){ Name="Peaches", Age=4}, null };

Friday, September 25, 2009

New features C# 3.0 :Implicitly Typed Local Variables

Local variables can be given an inferred "type" of var instead of an explicit type. The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement.

The following examples show various ways in which local variables can be declared with var:
// i is compiled as an int
var i = 5;
// s is compiled as a string
var s = "Hello";
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
// expr is compiled as IEnumerable
// or perhaps IQueryable
var expr = from c in customers
where c.City == "London"
select c;
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
// list is compiled as List
var list = new List();

It is important to understand that the var keyword does not mean “variant” and does not indicate that the variable is loosely typed, or late-bound. It just means that the compiler determines and assigns the most appropriate type.
The var keyword may be used in the following contexts:
  • On local variables (variables declared at method scope) as shown in the previous example.
  • In a for initialization statement. for(var x = 1; x < 10; x++)
  • In a foreach initialization statement. foreach(var item in list){...}
  • In a using Statement using (var file = new StreamReader("C:\\myfile.txt")) {...}
 The following restrictions apply to implicitly-typed variable declarations:
  • var can only be used when a local variable is declared and initialized in the same statement; the variable cannot be initialized to null, or to a method group or an anonymous function.
  • var cannot be used on fields at class scope.
  • Variables declared by using var cannot be used in the initialization expression. In other words, this expression is legal: int i = (i = 20); but this expression produces a compile-time error: var i = (i = 20);
  • Multiple implicitly-typed variables cannot be initialized in the same statement.
  • If a type named var is in scope, then the var keyword will resolve to that type name and will not be treated as part of an implicitly typed local variable declaration.

using Statement (C#)

using Statement-Defines a scope, outside of which an object or objects will be disposed.
Syntax: using (Font font1 = new Font("Arial", 10.0f)) { }
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.
The object can be declared in the using statement, as shown above, or before the using statement, like this:
Font font2 = new Font("Arial", 10.0f);
using (font2) { // use font2 }
Multiple objects can be used in with a using statement, but they must be declared inside the using statement, like this:
using (Font font3 = new Font("Arial", 10.0f),
font4 = new Font("Arial", 10.0f)) {// Use font3 and font4.}
Example: The following sample shows how a user-defined class can implement its own Dispose behavior. Note that your type must inherit from IDisposable.
using System;
class C : IDisposable
{
public void UseLimitedResource()
{ Console.WriteLine("Using limited resource..."); }
void IDisposable.Dispose()
{ Console.WriteLine("Disposing limited resource."); }
}
class Program
{
static void Main()
{
using (C c = new C())  { c.UseLimitedResource(); }
Console.WriteLine("Now outside using statement.");
Console.ReadLine();
}
}

Wednesday, August 26, 2009

Differences Between Shadowing and Overriding

Both Overriding and Shadowing are ways to alter the behaviour of members of a base class. Shadowing is a VB.NET concept. In C#, this concept is called Hiding, though there is a difference between the two.
When we do shadowing, we provide a new implementation to the base class member without overriding it. We may shadow a base class member in a derived class, by using the keyword shadows. The access level, return type, and the signature (means the datatypes of the arguments passed & the order of the types) of the derived class members which are shadowed, may differ from the base class.
In C#, we may achieve shadowing using the keyword new. However, when Hiding in C#, the access level, the signature, return type of the derived class must be same as the base class.
Overriding is the concept of providing a new implementation of derived class member as compared to its based class. In VB.NET, we do overriding using the overrides keyword, while in C#, overriding is achieved using the override keyword. For a class member to be overridable, we use the keyword virtual while defining it (in C#), and we use the keyword overridable (in VB.NET), though if we leave out specifying the overridable keyword, the member is overridable by default.
You can refer the MSDN also: http://msdn.microsoft.com/en-us/library/ms172785(VS.80).aspx for table of comparison.