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