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 };