Search content within the blog

Wednesday, May 25, 2011

Extension Methods in C#

.NET 3.5 is out which means all of the great features available in C# 3.0 are available to use now. Here's a quick list of the main language enhancements available in C# 3.0:
# Object Initializers
# Automatic Properties
# Extension Methods
# Anonymous Types
# Lambda Expressions
# LINQ
# Collection Initializers

Extension methods allow existing classes to be extended without relying on inheritance or having to change the class's source code. This means that if you want to add some methods into the existing String class you can do it quite easily. Here's a couple of rules to consider when deciding on whether or not to use extension methods:

*Extension methods cannot be used to override existing methods
*An extension method with the same name and signature as an instance method will not be called
*The concept of extension methods cannot be applied to fields, properties or events
*Use extension methods sparingly....overuse can be a bad thing!

Here's an example of creating an extension method in C# that adds a RemoveNonNumeric() method to the String class. Notice that the class is defined as static as well as the extension method itself. The "this" keyword in the parameter signature tells the compiler to add the extension method to the String class since "string" follows the keyword.

namespace StringExtensions
{
public static class StringExtensionsClass
{
public static string RemoveNonNumeric(this string s)
{
MatchCollection col = Regex.Matches(s, "[0-9]");
StringBuilder sb = new StringBuilder();
foreach (Match m in col)
sb.Append(m.Value);
return sb.ToString();
}
}


Here's an example of how the extension method can be used. You'll see that the namespace for the extension method class is imported. From there, the compiler treats the RemoveNonNumeric() method as if it was originally part of the standard System.String class.

using StringExtensions;
.
.
.
.
.
....
string phone = "123-123-1234";
string newPhone = phone.RemoveNonNumeric();

Saturday, May 14, 2011

Advantages of wcf service over web services.

As several people asking me the WCF benefits over web services, I outlined the points here

1.WCF supports more of WS-* standards than web services

2.As I mentioned in the article WCF supports multiple bindings HTTP,TCP,MSMQ,WS-HTTP etc where as web service supports only HTTP.

3.WCF can maintain transactions like COM+

4.It has JSON integration

5.It can be hosted on IIS,WAS, Self hosting and windows services

6.Web services have no instance management ie you can not have a singleton web service or session full webservice

Transact-SQL :- ROW_NUMBER()

Transact-SQL :- ROW_NUMBER()

While creating query we may need a column which will hold the sequential number like 1, 2, 3… Also we may need to show that sequential number according to a particular partition. In that situation we can use the ‘ROW_NUMBER’ keyword.

Below syntax can be followed :-


1. To get sequential number irrespective of any partition.

ROW_NUMBER ( ) OVER (<order_by_clause>)

SELECT ROW_NUMBER() OVER (ORDER BY [Col2] ASC) AS RowNo,
[Col1],[Col2],[col3] FROM [dbo].[demo_table];

Result will be:

RowNo Col1 Col2 col3
-------------------- -------------------- --------------------------------------------------
1 4 Andew 2009-03-01 00:00:00.000
2 8 Andew NULL
3 6 James 2009-07-01 00:00:00.000
4 3 John 2009-02-01 00:00:00.000
5 1 John 2009-06-24 00:00:00.000
6 2 Lee 2009-06-24 00:00:00.000
7 5 Steven 2009-06-24 00:00:00.000

2. To get sequential number within a partition.
ROW_NUMBER ( ) OVER (<partition_by_clause><order_by_clause>)

SELECT ROW_NUMBER() OVER (PARTITION BY [Col2] ORDER BY [Col2] ASC) AS RowNo,[Col1],[Col2],[col3] FROM [demo_table];

Result will be:

RowNo Col1 Col2 Col3
------------------- -------------------- ---------------------------------------------------
1 4 Andew 2009-03-01 00:00:00.000
2 8 Andew NULL
1 6 James 2009-07-01 00:00:00.000
1 3 John 2009-02-01 00:00:00.000
2 1 John 2009-06-24 00:00:00.000
1 2 Lee 2009-06-24 00:00:00.000
1 5 Steven 2009-06-24 00:00:00.000

Thursday, May 12, 2011

Assemblies in ASP.net

What is an assembly?

* An Assembly is a logical unit of code
* Assembly physically exist as DLLs or EXEs
* One assembly can contain one or more files
* The constituent files can include any file types like image files, text files etc. along with DLLs or EXEs
* When you compile your source code by default the exe/dll generated is actually an assembly
* Unless your code is bundled as assembly it can not be used in any other application
* When you talk about version of a component you are actually talking about version of the assembly to which the component belongs.
* Every assembly file contains information about itself. This information is called as Assembly Manifest.

What is assembly manifest?

* Assembly manifest is a data structure which stores information about an assembly
* This information is stored within the assembly file(DLL/EXE) itself
* The information includes version information, list of constituent files etc.

What is private and shared assembly?

The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.
What is Global Assembly Cache?

Global assembly cache is nothing but a special disk folder where all the shared assemblies will be kept. It is located under <drive>:\WinNT\Assembly folder.
How assemblies avoid DLL Hell?

As stated earlier most of the assemblies are private. Hence each client application refers assemblies from its own installation folder. So, even though there are multiple versions of same assembly they will not conflict with each other. Consider following example :

* You created assembly Assembly1
* You also created a client application which uses Assembly1 say Client1
* You installed the client in C:\MyApp1 and also placed Assembly1 in this folder
* After some days you changed Assembly1
* You now created another application Client2 which uses this changed Assembly1
* You installed Client2 in C:\MyApp2 and also placed changed Assembly1 in this folder
* Since both the clients are referring to their own versions of Assembly1 everything goes on smoothly

Now consider the case when you develop assembly that is shared one. In this case it is important to know how assemblies are versioned. All assemblies has a version number in the form:

major.minor.build.revision

If you change the original assembly the changed version will be considered compatible with existing one if the major and minor versions of both the assemblies match.

When the client application requests assembly the requested version number is matched against available versions and the version matching major and minor version numbers and having most latest build and revision number are supplied.
How do I create shared assemblies?

Following steps are involved in creating shared assemblies :

* Create your DLL/EXE source code
* Generate unique assembly name using SN utility
* Sign your DLL/EXE with the private key by modifying AssemblyInfo file
* Compile your DLL/EXE
* Place the resultant DLL/EXE in global assembly cache using AL utility

How do I create unique assembly name?

Microsoft now uses a public-private key pair to uniquely identify an assembly. These keys are generated using a utility called SN.exe (SN stands for shared name). The most common syntax of is :

sn -k mykeyfile.key

Where k represents that we want to generate a key and the file name followed is the file in which the keys will be stored.
How do I sign my DLL/EXE?

Before placing the assembly into shared cache you need to sign it using the keys we just generated. You mention the signing information in a special file called AssemblyInfo. Open the file from VS.NET solution explorer and change it to include following lines :

[assembly:AssemblyKeyFile("file_path")]

Now recompile the project and the assembly will be signed for you.

Note : You can also supply the key file information during command line compilation via /a.keyfile switch.
How do I place the assembly in shared cache?

Microsoft has provided a utility called AL.exe to actually place your assembly in shared cache.

AL /i:my_dll.dll

Now your dll will be placed at proper location by the utility.
Hands On...

Now, that we have understood the basics of assemblies let us apply our knowledge by developing a simple shared assembly.

In this example we will create a VB.NET component called SampleGAC ( GAC stands for Global Assembly Cache). We will also create a key file named sample.key. We will sign our component with this key file and place it in Global Assembly Cache.

* Step 1 : Creating our sample component

Here is the code for the component. It just includes one method which returns a string.

imports system

namespace BAJComponents
public class Sample
public function GetData() as string
return "hello world"
end function
end class
end namespace

* Step 2 : Generate a key file

To generate the key file issue following command at command prompt.

sn -k sample.key

This will generate the key file in the same folder

* Step 3 : Sign your component with the key

Now, wee will sign the assembly with the key file we just created.

vbc sampleGAC.vb /t:library /a.keyfile:sample.key

* Step 4 : Host the signed assembly in Global Assembly Cache

We will use AL utility to place the assembly in Global Assembly Cache.

AL /i:sampleGAC.dll

After hosting the assembly just go to WINNT\Assembly folder and you will find your assembly listed there. Note how the assembly folder is treated differently that normal folders.



*
Step 5 : Test that our assembly works

Now, we will create a sample client application which uses our shared assembly. Just create a sample code as listed below :

imports system
imports BAJComponents
public class SampleTest
shared sub main()
dim x as new sample
dim s as string="x".getdata()
console.writeline(s)
end sub
end class

Compile above code using :

vbc sampletest.vb /t:exe /r:<assembly_dll_path_here>

Now, copy the resulting EXE in any other folder and run it. It will display "Hello World" indicating that it is using our shared assembly.

Difference between Response.Redirect and Server.transfer

You can transfer current users page request to another page with two methods:

* Server.Transfer (HttpServerUtility.Transfer Method)
* Response.Redirect (HttpResponse.Redirect Method)

Its not always clear how these two approaches differ so let us try to clarify things a little:

Response.Redirect sends HTTP code 302 down to the users browser along with the new URL location of the wanted page.
HTTP Code 302 actually means ' The requested resource resides temporarily under a different URI'.
After browser receives this code it tries to open the new location of the resource that was suggested by the server.
This actually causes two requests to the server, first one to the original URL, and second to the new URL that is suggested via 302 response.
All the Query Strings and Form variables are lost during the redirect and they are not available to the redirected URL.

Also its important to say that the new URL can reside on the same server but also it can be on some other server and the redirected URL does not need to be .aspx page it can be regular HTML page also).

So we can us the Redirect method to redirect users request to another page on our server like this:

Response.Redirect("newPage.html");

or to redirect our it to some other server like this:

Response.Redirect("http://www.someotherserver.com/newPage.aspx");


In contrast to all this when we call Server.Transfer we do not initiate another request to the server, but the original request is simply rewritten and transfered to some other page on the same server.
(This off course means that we can use it only to transfer requests to the pages on the same server, not to some other servers and we can only transfer to .aspx pages and not other page types like HTML, php etc).

All posted Form variables and query strings can optionally remain available to the second Page where we transfered request (if we use second overload Server.Transfer(string path, bool preserveForm) and supply true for the second parameter).
Otherwise the Form Variables and Query String are cleared just like when we use Redirect.
WARNING: If you use this method to preserve Query String and Form variables and receive error: "View State Is Invalid" its because your EnableViewStateMac attribute of the <pages> element is set to true. More on this error on this page: PRB: "View State Is Invalid" Error Message When You Use Server.Transfer

Its also important to note that because of the way Server.Transfer works, after the transfer, the URL shown in the users Web Browser remains the original one that was requested, because browser has no knowledge that its request was transfered (transfer occurs on the server side).

TIP: One thing to be careful about when using the Server.Transfer is to clear the the HttpResponse object with Response.Clear method on the transfered page to avoid any output from the first page to be shown on the second page.

So now that we know what are the similarities and differences between these two approaches we can try to use them wisely.

Here is the summary:

Response.Redirect should be used when:

* we want to redirect the request to some plain HTML pages on our server or to some other web server
* we don't care about causing additional roundtrips to the server on each request
* we do not need to preserve Query String and Form Variables from the original request
* we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)

Server.Transfer should be used when:

* we want to transfer current page request to another .aspx page on the same server
* we want to preserve server resources and avoid the unnecessary roundtrips to the server
* we want to preserve Query String and Form Variables (optionally)
* we don't need to show the real URL where we redirected the request in the users Web Browser

Sunday, May 8, 2011

Reflection in c# - Detailed examples

The Reflection API allows a C# program to inspect and manipulate itself. It can be used to effectively find all the types in an assembly and/or dynamically invoke methods in an assembly. It can at times even be used to emit Intermediate Language code on the fly so that the generated code can be executed directly.

Reflection is also used to obtain information about a class and its members. Reflection can be used to manipulate other objects on the .NET platform.

The Reflection API uses the System.Reflection namespace, with the Type class to identify the Type of the Class being reflected, and fields of a struct or enum represented by the FieldInfo class, Members of the reflected class represented by the MemberInfo class, Methods of a reflected class represented by the MethodInfo class, and parameters to Methods represented by the ParameterInfo class.

The Activator class's CreateInstance() method is used to dynamically invoke instances on the fly. Dynamic Invocation is very useful in providing a very late-binding architecture, where one component's runtime can be integrated with other component runtimes.

We will illustrate the use of the Reflection API in three different ways:

1. Obtaining Class and Type Information from an Assembly

2. Obtaining Member Information from a Class

3. Dynamically Invoking Methods from Classes in an Assembly

Develop the Test Application

Before we start our forays into C# Reflection and Dynamic Invocation, let us develop our test applications that we'll use to test our Reflection code. Develop an interface called IBase. ImplementationOne and ImplementationTwo are classes that implement the IBase interface and are each compiled into separate assemblies.

1. Develop our Test Base Interface : IBase

/**
* File: IBase.cs
* Article: C# Reflection and Dynamic Method Invocation
* Copyright (c) 2000, Gopalan Suresh Raj. All Rights Reserved.
*/

namespace com.icommware {

/**
* An enumeration of Color Values
*/
enum ColorEnumeration {
RED = 1,
GREEN = 2,
BLUE = 3
}

/**
* An Interface with 2 methods
*/
interface IBase {

string execute (string data);
double compute (int param1, double param2);
}
}


2. Develop a Test Implementation for the IBase Test Interface : ImplementationOne
/**
* File: ImplementionOne.cs
* Article: C# Reflection and Dynamic Method Invocation
* Copyright (c) 2000, Gopalan Suresh Raj. All Rights Reserved.
* Compile with: csc /target:library ImplementationOne.cs IBase.cs
*/

using System;

namespace com.icommware {

/**
* A Class that implements the IBase interface
*/
class ImplementationOne : IBase {

string remark = "Remark of ImplementationOne";
static int DELTAFACTOR = 10;

ImplementationOne () {
Console.WriteLine ("Invoking ImplementationOne...");
}

public string execute (string data) {
remark = data;
Console.WriteLine ("ImplementationOne's execute() remark is : {0}", remark);
return remark;
}

public double compute (int param1, double param2) {
Console.WriteLine ("ImplementationOne's compute() method invoked...");
return param1*param2*DELTAFACTOR;
}
}

/**
* A generic Structure
*/
struct StructOne {
int x;
double y;

double assign () {
x = 10;
y = 2.8;
return x*y;
}
}
}

3. Compile the Test Application as a Library (DLL) : ImplementationOne.DLL
MS-DOS Command Prompt
H:\gopalan\Reflection>
H:\gopalan\Reflection>csc /target:library ImplementationOne.cs IBase.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.


H:\gopalan\Reflection>
H:\gopalan\Reflection>csc /target:library ImplementationTwo.cs IBase.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.

Obtaining All Classes and Their Type Information from an Assembly

1. Develop an Application that Reflects Types: ReflectTypesusing System;
using System.Reflection;

/**
* Develop a class that can Reflect all the Types available in an Assembly
*/
class ReflectTypes {

public static void Main (string[] args) {

// List all the types in the assembly that is passed in as a parameter
Assembly assembly = Assembly.LoadFrom (args[0]);

// Get all Types available in the assembly in an array
Type[] typeArray = assembly.GetTypes ();

Console.WriteLine ("The Different Types of Classes Available in {0} are:", args[0]);
Console.WriteLine ("_____");
// Walk through each Type and list their Information
foreach (Type type in typeArray) {
// Print the Class Name
Console.WriteLine ("Type Name : {0}", type.FullName);
// Print the name space
Console.WriteLine ("Type Namespace : {0}", type.Namespace);
// Print the Base Class Name
Console.WriteLine ("Type Base Class : {0}", (type.BaseType != null)?type.BaseType.FullName:"No Base Class Found...");
Console.WriteLine ("_____");
}
}
}

2. Compile and Run ReflectTypes (ReflectTypes.EXE) on Our Test Library (ImplementationOne.DLL)
H:\gopalan\Reflection>
H:\gopalan\Reflection>csc ReflectTypes.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.


H:\gopalan\Reflection>
H:\gopalan\Reflection>ReflectTypes ImplementationOne.dll
The Different Types of Classes Available in ImplementationOne.dll are:
_____
Type Name : com.icommware.ColorEnumeration
Type Namespace : com.icommware
Type Base Class : System.Enum
_____
Type Name : com.icommware.IBase
Type Namespace : com.icommware
Type Base Class : No Base Class Found...
_____
Type Name : com.icommware.StructOne
Type Namespace : com.icommware
Type Base Class : System.ValueType
_____
Type Name : com.icommware.ImplementationOne
Type Namespace : com.icommware
Type Base Class : System.Object
_____


Obtaining Member Information from a Class

1. Develop an Application that Reflects Methods: ReflectMethods

using System;
using System.Reflection;

namespace com.icommware {

/**
* An enumeration of Account Types
*/
enum AccountEnumeration {
CHECKING = 1,
SAVINGS = 2,
}

/**
* A Class that implements the IBase interface
*/
class ImplementationTwo : IBase {
string remark = "Remark of ImplementationTwo";
static int DELTAFACTOR = 100;

ImplementationTwo () {
Console.WriteLine ("Invoking ImplementationTwo ...");
}

public string execute (string data) {
remark = data;
Console.WriteLine ("ImplementationTwo's execute() remark is : {0}", remark);
return remark;
}

public double compute (int param1, double param2) {
Console.WriteLine ("ImplementationTwo's compute() method invoked...");
return param1*param2*DELTAFACTOR;
}
}

/**
* A generic Structure
*/
struct StructTwo {
double x;
int y;

double assign () {
x = 8.2;
y = 10;
return x*y;
}
}
}

/**
* Develop a class that can Reflect all the Types available in an Assembly
*/
class ReflectMethods {

public static void Main (string[] args) {

// retrieve information about AccountEnumeration
Console.WriteLine ("Names and Values of the com.icommware.AccountEnumeration are:");
Type type = typeof (com.icommware.AccountEnumeration );

// Create an instance of AccountEnumeration in Memory
object accountEnum = Activator.CreateInstance (type);

// List the names and values available in the AccountEnumeration enum
foreach (FieldInfo fieldInfo in type.GetFields (BindingFlags.LookupAll)) {
object value = fieldInfo.GetValue (accountEnum);
Console.WriteLine ("{0} = {1}", fieldInfo, value);
}
Console.WriteLine ("_____");

// retrieve information about ImplementationTwo Class
Console.WriteLine ("The Members of the com.icommware.ImplementationTwo Class are:");
type = typeof (com.icommware.ImplementationTwo);

// List the members of the ImplementationTwo Class
foreach (MemberInfo memberInfo in type.GetFields (BindingFlags.LookupAll)) {
Console.WriteLine ("{0}", memberInfo);
}
Console.WriteLine ("_____");

// Walk through the methods of the ImplementationTwo Class
Console.WriteLine ("The Methods of the com.icommware.ImplementationTwo Class are:");
foreach (MethodInfo methodInfo in type.GetMethods (BindingFlags.LookupAll)) {
// Print the Method Signature
Console.WriteLine ("{0}", methodInfo);
// Walk through the method parameters
foreach (ParameterInfo parameterInfo in methodInfo.GetParameters ()) {
// Print the Parameter Type and the Parameter Name
Console.WriteLine (" Param: {0} {1}", parameterInfo.ParameterType, parameterInfo.Name);
}
Console.WriteLine ("_____");
}


// retrieve information about StructTwo Class
Console.WriteLine ("The Members of the com.icommware.StructTwo Class are:");
type = typeof (com.icommware.StructTwo);

// List the members of the StructTwo Class
foreach (MemberInfo memberInfo in type.GetFields (BindingFlags.LookupAll)) {
Console.WriteLine ("{0}", memberInfo);
}
Console.WriteLine ("_____");
// Walk through the methods of the StructTwo Class
Console.WriteLine ("The Methods of the com.icommware.StructTwo Class are:");
foreach (MethodInfo methodInfo in type.GetMethods (BindingFlags.LookupAll)) {
// Print the Method Signature
Console.WriteLine ("{0}", methodInfo);
// Walk through the method parameters
foreach (ParameterInfo parameterInfo in methodInfo.GetParameters ()) {
// Print the Parameter Type and the Parameter Name
Console.WriteLine (" Param: {0} {1}", parameterInfo.ParameterType, parameterInfo.Name);
}
Console.WriteLine ("_____");
}
}
}


2. Compile and Run ReflectMethods (ReflectMethods.EXE)

H:\gopalan\Reflection>
H:\gopalan\Reflection>csc ReflectMethods.cs IBase.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.


H:\gopalan\Reflection>ReflectMethods
Names and Values of the com.icommware.AccountEnumeration are:
Int32 value__ = 0
com.icommware.AccountEnumeration CHECKING = 1
com.icommware.AccountEnumeration SAVINGS = 2
_____
The Members of the com.icommware.ImplementationTwo Class are:
System.String remark
Int32 DELTAFACTOR
_____
The Methods of the com.icommware.ImplementationTwo Class are:
Double compute (Int32, Double)
Param: Int32 param1
Param: Double param2
_____
System.String execute (System.String)
Param: System.String data
_____
Void Finalize ()
_____
Int32 GetHashCode ()
_____
Boolean Equals (System.Object)
Param: System.Object obj
_____
System.String ToString ()
_____
System.Type GetType ()
_____
System.Object MemberwiseClone ()
_____
The Members of the com.icommware.StructTwo Class are:
Double x
Int32 y
_____
The Methods of the com.icommware.StructTwo Class are:
Void Finalize ()
_____
Int32 GetHashCode ()
_____
Boolean Equals (System.Object)
Param: System.Object obj
_____
System.String ToString ()
_____
Double assign ()
_____
System.Type GetType ()
_____
System.Object MemberwiseClone ()
_____


Dynamically invoking methods from a class in an Assembly

We use Reflection to open all the Assemblies on the command line, search for Classes that implement the com.icommware.IBase interface, create an instance of that class and invoke the compute() method on the assembly.

1. Develop an Application that dynamically invokes methods from an Assembly
using System;
using System.Reflection;
using com.icommware;

class DynamicInvocation {

public static void invokeProcess (string assemblyName) {
Console.WriteLine ("Loading {0} into memory...", assemblyName);
Assembly assembly = Assembly.LoadFrom (assemblyName);

// Walk through each type in the assembly
foreach (Type type in assembly.GetTypes ()) {
// Pick up a class
if (type.IsClass == true) {
Console.WriteLine ("...Found Class : {0}", type.FullName);

// If it does not implement the IBase Interface, skip it
if (type.GetInterface ("com.icommware.IBase") == null) {
continue;
}

// If however, it does implement the IBase Interface,
// create an instance of the object
object ibaseObject = Activator.CreateInstance (type);

// Create the parameter list
object[] arguments = new object [] {10, 17.11};
object result;
// Dynamically Invoke the Object
Console.WriteLine ("......Dynamically Invoking compute() on {0} Class", type.FullName);
result = type.InvokeMember ("compute",
BindingFlags.Default | BindingFlags.InvokeMethod,
null,
ibaseObject,
arguments);

Console.WriteLine ("......Result is: {0}", result);
}
}
}

public static void Main (string[] args) {
foreach (string argument in args) {
invokeProcess (argument);
}
}

}

2. Compile and Run DynamicInvocation (DynamicInvocation.EXE)
H:\gopalan\Reflection>
H:\gopalan\Reflection>csc DynamicInvocation.cs IBase.cs
Microsoft (R) C# Compiler Version 7.00.8905 [NGWS runtime 2000.14.1812.10]
Copyright (C) Microsoft Corp 2000. All rights reserved.


H:\gopalan\Reflection>DynamicInvocation ImplementationOne.DLL ReflectMethods.EXE
Loading ImplementationOne.DLL into memory...
...Found Class : com.icommware.ImplementationOne
Invoking ImplementationOne...
......Dynamically Invoking compute() on com.icommware.ImplementationOne Class
ImplementationOne's compute() method invoked...
......Result is: 1711
Loading ReflectMethods.EXE into memory...
...Found Class : com.icommware.ImplementationTwo
Invoking ImplementationTwo ...
......Dynamically Invoking compute() on com.icommware.ImplementationTwo Class
ImplementationTwo's compute() method invoked...
......Result is: 17110
...Found Class : ReflectMethods

Reflection Examples [C#]

This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.
Create instance from assembly that is in your project References

The following examples create instances of DateTime class from the System assembly.
[C#]

// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));


[C#]

// create instance of DateTime, use constructor with parameters (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),
new object[] { 2008, 7, 4 });


Create instance from dynamically loaded assembly

All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
[C#]

namespace Test
{
public class Calculator
{
public Calculator() { ... }
private double _number;
public double Number { get { ... } set { ... } }
public void Clear() { ... }
private void DoClear() { ... }
public double Add(double number) { ... }
public static double Pi { ... }
public static double GetPi() { ... }
}
}


Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).
[C#]

// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");


[C#]

// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");


[C#]

// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);


[C#]

// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");


[C#]

// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);


[C#]

// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);


[C#]

// get info about static property: public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");


[C#]

// get value of static property: public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);


[C#]

// invoke public instance method: public void Clear()
calcType.InvokeMember("Clear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, null);


[C#]

// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null);


[C#]

// invoke public instance method: public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
null, calcInstance, new object[] { 20.0 });


[C#]

// invoke public static method: public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
null, null, null);


[C#]

// get value of private field: private double _number
double value = (double)calcType.InvokeMember("_number",
BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
null, calcInstance, null);

Reflection in c# - part I

Wikipedia says that "In computer science, reflection is the process by which a computer program can observe and modify its own structure and behaviour". This is exactly how Reflection in C# works, and while you may not realize it at this point, being able to examine and change information about your application during runtime, offers huge potential. Reflection, which is both a general term, as well as the actual name of the reflection capabilities in C#, works very, very well, and it's actually not that hard to use. In the next couple of chapters, we will go more into depth about how it works and provide you with some cool examples, which should show you just how useful Reflection is.

However, to get you started and hopefully interested, here is a small example. It solves a question that I have seen from many newcomers to any programming language: How can I change the value of a variable during runtime, only by knowing its name? Have a look at this small demo application for a solution, and read the next chapters for an explanation of the different techniques used.

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
class Program
{
private static int a = 5, b = 10, c = 20;

static void Main(string[] args)
{
Console.WriteLine("a + b + c = " + (a + b + c));
Console.WriteLine("Please enter the name of the variable that you wish to change:");
string varName = Console.ReadLine();
Type t = typeof(Program);
FieldInfo fieldInfo = t.GetField(varName, BindingFlags.NonPublic | BindingFlags.Static);
if(fieldInfo != null)
{
Console.WriteLine("The current value of " + fieldInfo.Name + " is " + fieldInfo.GetValue(null) + ". You may enter a new value now:");
string newValue = Console.ReadLine();
int newInt;
if(int.TryParse(newValue, out newInt))
{
fieldInfo.SetValue(null, newInt);
Console.WriteLine("a + b + c = " + (a + b + c));
}
Console.ReadKey();
}
}
}
}

Try running the code and see how it works. Besides the lines where we use the actual Reflection, it's all very simple. Now, go to the next chapter for some more theory on how it works.



The right Type
The Type class is the foundation of Reflection. It serves as runtime information about an assembly, a module or a type. Fortunately, obtaining a reference to the Type of an object is very simply, since every class that inherits from the Object class, has a GetType() method. If you need information about a non-instantiated type, you may use the globally available typeof() method, which will do just that. Consider the following examples, where we use both approaches:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
string test = "test";
Console.WriteLine(test.GetType().FullName);
Console.WriteLine(typeof(Int32).FullName);
Console.ReadKey();
}
}
}

We use the GetType() method on our own variable, and then we use the typeof() on a known class, the Int32. As you can see, the result in both cases is a Type object, for which we can read the FullName property.

At some point, you might even only have the name of the type that you're looking for. In that case, you will have to get a reference to it from the proper assembly. In the next example, we get a reference to the executing assembly, that is, the assembly from where the current code is being executed from, and then we list all of it's types:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.GetExecutingAssembly();
Type[] assemblyTypes = assembly.GetTypes();
foreach(Type t in assemblyTypes)
Console.WriteLine(t.Name);
Console.ReadKey();
}
}

class DummyClass
{
//Just here to make the output a tad less boring :)
}
}

The output will be the name of the two declared classes, Program and DummyClass, but in a more complex application, the list would probably be more interesting. In this case, we only get the name of the type, but obviously we would be able to do a lot more, with the Type reference that we get. In the next chapters, I will show you a bit more on what we can do with it.

Instantiating a class
So far, we have worked with .NET types or objects already instantiated. But with Reflection, we can actually do the instantiation at runtime as well, knowing the name of the class we wish to instantiate. There are several ways of doing it, but I prefer getting a reference to the constructor that I wish to use, invoke it, and then use the returned value as my instance. Here's an example of doing just that. Code first, then I will explain it all:

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ReflectionTest
{
class Program
{
static void Main(string[] args)
{
Type testType = typeof(TestClass);
ConstructorInfo ctor = testType.GetConstructor(System.Type.EmptyTypes);
if(ctor != null)
{
object instance = ctor.Invoke(null);
MethodInfo methodInfo = testType.GetMethod("TestMethod");
Console.WriteLine(methodInfo.Invoke(instance, new object[] { 10 }));
}
Console.ReadKey();
}
}

public class TestClass
{
private int testValue = 42;

public int TestMethod(int numberToAdd)
{
return this.testValue + numberToAdd;
}
}
}

I have defined a simple class for testing this, called TestClass. It simply contains a private field and a public method. The method returns the value of the private property, with the value of the parameter added to it. Now, what we want is to create a new instance of this TestClass, call the TestMethod and output the result to the console.

In this example, we have the luxury of being able to use the typeof() directly on the TestClass, but at some point, you may have to do it solely by using the name of the desired class. In that case, you can get a reference to it through the assembly where it is declared, as demonstrated in the chapter about Type.

So, with a Type reference to the class, we ask for the default constructor by using the GetConstructor() method, passing System.Type.EmptyTypes as a parameter. In case we wanted a specific constructor, we would have to provide an array of Type's, each defining which parameter the constructor we were looking for, would take.

Once we have a reference to the constructor, we simply call the Invoke() method to create a new instance of the TestClass class. We pass null as the parameter to Invoke(), since we're not looking to specify any parameters. We use the GetMethod(), along with the name of the method we want, to get the TestMethod() function, and then we once again use the magic of the Invoke() method to call this function. This time we need to specify a parameter, in the form of an array of objects. We do that on-the-fly, specifying the number 10 as the only parameter we need, and we then output the result of the method invocation. All of this through the magic of Reflection!


A Reflection based settings class
Okay, so I thought that I would end this part of the tutorial about Reflection, with a cool and useful example. It's a bit bigger than the usual examples here at the site, but hopefully you will find it really useful. It uses a bunch of the stuff that we have looked into during the last couple of chapters, so hopefully you can keep up.

A common scenario when creating any sort of application, is the desire to save the users settings. When you get several settings, you will probably create a Settings class, which will handle loading and saving of the desired settings. Each time you need a new setting in your Settings class, you will have to update the Load() and Save() methods, to include this new setting. But hey, why not let the Settings class discover its own properties and then load and save them automatically? With Reflection, it's quite easy, and if you have read the other chapters in the Reflection section of this tutorial, you should be able to understand the following example.

To make it fit better into a small example, I am saving information about a person instead of application settings, but hopefully you will get the general idea anyway. Please be aware that using Reflection WILL be slower than reading and writing known properties manually, so you should consider when to use it and when to opt for a faster approach! Also, in our example, we use a simple text file for storing even simpler values, only separated by a | (pipe character). If you're using this for real world stuff, you will probably want a better format for your data, perhaps XML. And of course, there is not much error handling, so you should probably add some of that as well.

Okay, let's get started. First, our Person class, which you can simply rename to Settings or something like that, to make it more useful to you:

public class Person
{
private int age = -1;
private string name = String.Empty;

public void Load()
{
if(File.Exists("settings.dat"))
{
Type type = this.GetType();

string propertyName, value;
string[] temp;
char[] splitChars = new char[] { '|' };
PropertyInfo propertyInfo;

string[] settings = File.ReadAllLines("settings.dat");
foreach(string s in settings)
{
temp = s.Split(splitChars);
if(temp.Length == 2)
{
propertyName = temp[0];
value = temp[1];
propertyInfo = type.GetProperty(propertyName);
if(propertyInfo != null)
this.SetProperty(propertyInfo, value);
}
}
}
}

public void Save()
{
Type type = this.GetType();
PropertyInfo[] properties = type.GetProperties();
TextWriter tw = new StreamWriter("settings.dat");
foreach(PropertyInfo propertyInfo in properties)
{
tw.WriteLine(propertyInfo.Name + "|" + propertyInfo.GetValue(this, null));
}
tw.Close();
}

public void SetProperty(PropertyInfo propertyInfo, object value)
{
switch(propertyInfo.PropertyType.Name)
{
case "Int32":
propertyInfo.SetValue(this, Convert.ToInt32(value), null);
break;
case "String":
propertyInfo.SetValue(this, value.ToString(), null);
break;
}
}

public int Age
{
get { return age; }
set { age = value; }
}

public string Name
{
get { return name; }
set { name = value; }
}
}

Okay, there's a lot of stuff, I know. But I will help you through the entire class. First of all, we have a couple of private fields, for holding information about our person. In the bottom of the class, we have the corresponding public properties which uses the private fields of course.

We also have a Load() method. It looks for the file settings.dat, and if it exists, it reads the entire file and places each line of it in an array of strings. Now, we run through each setting line, and splits it up into two parts: A property name and a value part. If both is present, we simply use the Type object to get the property with the property name, and then we set the value for it, using our own SetProperty method.

The SetProperty() method looks at the type of the property about to be changed, and then acts correspondingly. Right now, it only supports integers and strings, but as you probably realize, extending this support would be quite easy.

The Save() method gets an array of PropertyInfo instances, one for each of the defined properties on the Person class, and then uses a TextWriter to write each property, and its value, to the data file.

Now we just need some code to use this class. This small application will try to load the person from the settings file, and if it doesn't succeed, the user is prompted for the information:

class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Load();
if((person.Age > 0) && (person.Name != String.Empty))
{
Console.WriteLine("Hi " + person.Name + " - you are " + person.Age + " years old!");
}
else
{
Console.WriteLine("I don't seem to know much about you. Please enter the following information:");
Type type = typeof(Person);
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo propertyInfo in properties)
{
Console.WriteLine(propertyInfo.Name + ":");
person.SetProperty(propertyInfo, Console.ReadLine());
}
person.Save();
Console.WriteLine("Thank you! I have saved your information for next time.");
}
Console.ReadKey();
}
}

Everything here is pretty trivial, except for the part where we ask the user for information. Once again, we use Reflection, to get all the public properties of the Person class, and then ask for each of them.

Defining a custom Attribute in C#

namespace CustomAttributes
{
// create custom attribute to be assigned to class members
[AttributeUsage(AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class BugFixAttribute : System.Attribute
{
// attribute constructor for positional parameters
public BugFixAttribute
(
int bugID,
string programmer,
string date
)
{
this.BugID = bugID;
this.Programmer = programmer;
this.Date = date;
}
// accessors
public int BugID { get; private set; }
public string Date { get; private set; }
public string Programmer { get; private set; }
// property for named parameter
public string Comment { get; set; }
}
// ********* assign the attributes to the class ********
[BugFixAttribute(121, "Jesse Liberty", "01/03/08")]
[BugFixAttribute(107, "Jesse Liberty", "01/04/08",
Comment = "Fixed off by one errors")]
public class MyMath
{
public double DoFunc1(double param1)
{
return param1 + DoFunc2(param1);
}
public double DoFunc2(double param1)
{
return param1 / 3;
}
}
public class Tester
{
static void Main(string[] args)
{
MyMath mm = new MyMath( );
Console.WriteLine("Calling DoFunc(7). Result: {0}",
mm.DoFunc1(7));
}
}
}
Output:
Calling DoFunc(7). Result: 9.3333333333333333

Difference between a singleton and static in C#

Advantages of singletons

Singletons preserve the conventional class approach, and don't require that you use the static keyword everywhere. They may be more demanding to implement at first, but will greatly simplify the architecture of your program. Unlike static classes, we can use singletons as parameters or objects.

Using singleton as parameter [C#]

//
// We want to call a function with this structure as an object.
// Get a reference from the Instance property on the singleton.
//
SiteStructure site = SiteStructure.Instance;
OtherFunction(site); // Use singleton as parameter.

Use singletons with interfaces

You can use singletons with interfaces just like any other class. In C#, an interface is a contract, and objects that have an interface must meet all of the requirements of that interface.

Singletons used with interface [C#]

/// <summary>
/// Stores signatures of various important methods related to the site.
/// </summary>
public interface ISiteInterface
{
};

/// <summary>
/// Skeleton of the singleton that inherits the interface.
/// </summary>
class SiteStructure : ISiteInterface
{
// Implements all ISiteInterface methods.
// [omitted]
}

/// <summary>
/// Here is an example class where we use a singleton with the interface.
/// </summary>
class TestClass
{
/// <summary>
/// Sample.
/// </summary>
public TestClass()
{
// Send singleton object to any function that can take its interface.
SiteStructure site = SiteStructure.Instance;
CustomMethod((ISiteInterface)site);
}

/// <summary>
/// Receives a singleton that adheres to the ISiteInterface interface.
/// </summary>
private void CustomMethod(ISiteInterface interfaceObject)
{
// Use the singleton by its interface.
}
}

Reusing the singleton. Here we can use the singleton on any method that accepts the interface. We don't need to rewrite anything over and over again.

Implementing the Singleton Pattern in C#

Implementing the Singleton Pattern in C#

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

* A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
* The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
* A static variable which holds a reference to the single created instance, if any.
* A public static means of getting the reference to the single created instance, creating one if necessary.

Note that all of these implementations also use a public static property Instance as the means of accessing the instance. In all cases, the property could easily be converted to a method, with no impact on thread-safety or performance.
First version - not thread-safe

// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.
Second version - simple thread-safety

public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.
Third version - attempted thread-safety using double-check locking

// Bad code! Do not use!
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();

Singleton()
{
}

public static Singleton Instance
{
get
{
if (instance==null)
{
lock (padlock)
{
if (instance==null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
}

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

* It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model underwent a reworking for version 1.5, but double-check locking is still broken after this without a volatile variable (as in C#).
* Without any memory barriers, it's broken in the ECMA CLI specification too. It's possible that under the .NET 2.0 memory model (which is stronger than the ECMA spec) it's safe, but I'd rather not rely on those stronger semantics, especially if there's any doubt as to the safety. Making the instance variable volatile can make it work, as would explicit memory barrier calls, although in the latter case even experts can't agree exactly which barriers are required. I tend to try to avoid situations where experts don't agree what's right and what's wrong!
* It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
* It still doesn't perform as well as the later implementations.

Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{
static readonly Singleton instance=new Singleton();

// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}

Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

* It's not as lazy as the other implementations. In particular, if you have static members other than Instance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
* There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
* The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the property entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a property in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)
Fifth version - fully lazy instantiation

public sealed class Singleton
{
Singleton()
{
}

public static Singleton Instance
{
get
{
return Nested.instance;
}
}

class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}

internal static readonly Singleton instance = new Singleton();
}
}

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in Instance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.
Performance vs laziness

In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a (relatively) significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. (See below for more on performance, however.)
Exceptions

Sometimes, you need to do work in a singleton constructor which may throw an exception, but might not be fatal to the whole application. Potentially, your application may be able to fix the problem and want to try again. Using type initializers to construct the singleton becomes problematic at this stage. Different runtimes handle this case differently, but I don't know of any which do the desired thing (running the type initializer again), and even if one did, your code would be broken on other runtimes. To avoid these problems, I'd suggest using the second pattern listed on the page - just use a simple lock, and go through the check each time, building the instance in the method/property if it hasn't already been successfully built.

Saturday, May 7, 2011

Using Response.Redirect and Response.End in Try...Catch block

In ASP.NET if you are using Response.End - Used for terminating page execution or Response.Redirect - used for redirecting page to some other page, and you are including these statements in TRY... CATCH block here is what you need to remember.

Problem:

When Response.Redirect or Response.End is written in TRY block, code in catch block is executed.

Reason:

ASP.NET executes these 2 methods on Response object by throwing ThreadAbort Exception. When written in simple Try...Catch block this results in Catch block catching this exception and processing code written in catch block. This causes unwanted code execution e.g. error logging or genric error display code which is generally written in Catch block.

Solution:

You need to handle ThreadAbort exception separately and do nothing if it is thrown. Refer following code patch:

try
{
// Your actual code

Response.End();
}
catch (ThreadAbortException exc)
{
// This should be first catch block i.e. before generic Exception
// This Catch block is to absorb exception thrown by Response.End
}
catch (Exception exc)
{
// Write actual error handling code here
}

Improve Perfomance in ASP.net

While developing any web site, one should keep some points in mind.

1) Set debug=false under compilation as follows:

<compilation default Language="c#" debug="false">

2) Use Server.Transfer instead of Response.Redirect.

3) Always check Page.IsValid when using Validator Controls

4) Use Foreach loop instead of For loop for String Iteration.

5) Use Client-Side Validation. (but not all the time you have to validate even on the server side)

6) Check “Page.IsPostBack”. To avoid repetition code execution.

7) GIF and PNG are similar, but PNG typically produces a lower file size. (True, but some browsers not supporting PNG format)

8) Use the AppOffline.htm when updating binaries

9) Turn off Tracing unless until required. (by default it's off, use on the pages where it's required)

<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>

10) Precompiled pages and disable AutoEventWireup; setting the AutoEventWireup attribute to false in the Machine.config file.

11) Turn off Session State, if not required.

<sessionstate timeout="20" cookieless="false" mode="Off" stateconnectionstring="tcpip=127.0.0.1:42424" sqlconnectionstring="data source=127.0.0.1;Trusted_Connection=no">

12) Select the Release mode before making the final Build for your application.

This option is available in the Top Frame just under the Window Menu option. By default, the Mode is Debug

13) Disable ViewState when not required.

EnableViewState="false"

14) Avoid frequent round trips to the Database.

15) Use Caching to improve the performance of your application.

16) Validate all Input received from the Users.

17) Use Finally Method to kill resources. (But not in the case of using)

18) The String and Stringbuilder Magic.

It is nice to use Stringbuilder instead of String when string are Amended. Strings occupy different memory location in every time of amended where stringbuilder use single memory location

19) Never use object value directly; first get object value in local variable and then use. It takes more time then variable reading.

20) Avoid Exceptions: Use If condition (if it is check proper condition)

21) Code optimization: Avoid using code like x = x +1; it is always better to use x+=1.

22) Data Access Techniques: DataReaders provide a fast and efficient method of data retrieval. DataReader is much faster than DataSets as far as performance is concerned

23) Before doing a bulky ASP code processing, you can check to make sure Response.IsClientConnected.

24) As always, avoid session variables because each ASP page runs in a different thread and session calls will be serialized one by one. So, this will slow down the application. Instead of session variables you can use the QueryString collection or hidden variables in the form which holds the values.

25) Enabling buffering will improve the performance, like

<% response.buffer=true %>

Then use: <% response.flush=true %>


26) Use Repeater control instead of DataGrid , DataList, Because It is efficient, customizable, and programmable.

27) Data listing is more time consume when large data are retrieve from database.

Paging will display only particular data but take load of all data.

Fetch only data that is needed for current page.

28) Avoid Inline JavaScript and CSS

29) Use single css file instead of multiple css file.

Try your best to combine all your CSS based classes into a single .css file as lot of .css files will cause a large amount of requests, regardless of the file sizes.

.css files are normally cached by browsers, so a single and heavy .css file doesn’t cause a long wait on each page request.

Inline .css classes could make HTML heavy, so again: go ahead with a single.css file.

30) Reduce cookie size

31) Compress CSS, JavaScript and Images

Online compressors are available; to compress file please refers following web and Replace your file content with optimize code.

http://iceyboard.no-ip.org/projects/css_compressor for CSS compression

www.xtreeme.com/javascript-optimizer/ . For JS Compression

32 .Use Cache appropriately

i. Page output caching:

<%@ OutputCache Duration="3600" VaryByParam="none" %>

ii. Page fragment caching:

Write a Page output caching code into each User Control

iii. Data caching:

<script language="C#" runat="server">

Protected void Page_Load (Object src, EventArgs e) {

DataView dv = (DataView) Cache. Get ("EmployeesDataView");

If (dv == null) { // wasn't thereSqlConnection conn =

new SqlConnection ("server=localhost;uid=sa;pwd=;database=Test");

SqlDataAdapter da =new SqlDataAdapter ("select * from Employees", conn);

Dataset ds = new DataSet();da.Fill(ds, "Employees");

dv = ds.Tables["Employees"].DefaultView;

Cache.Insert ("EmployeesDataView", dv);conn.Close();}

Else

Response.Write ("<h2>Loaded employees from data cache! </h2>");

lb1.DataSource = dv;

lb1.DataTextField = "Name";

lb1.DataValueField = "Age";

DataBind () ;}

</script>

33) Use server side compression software such as Port80s http://www.port80software.com/products/httpzip/

34) Usage of "using" and I don't know why it's not yet published.

35) Don't make the member variables public or proteted, try to keep private and use public/protected as properties.

36) Use strString=string.Empty instead of strString="" . [And perhaps instead of strString=null also (?)]

37) Make your page files as light as possible. That is try to avoid unnecessary markups, e.g. use div elements instead of tables.

38) Write static messages in div and make it visible when necessary. This is faster than letting server set Text property of your label or div.

39) Retrieve data from database at once, if possible. Don't add up to database trip as far as possible. For this, combine the datafields from different tables and select them.

40) Use short ID name for WebControl.

Page Life Cycle in ASP.NET

When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, I will discuss in detail the ASP.NET page life cycle Events

(1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

using System;

using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page{ protected void Page_PreInit(object sender, EventArgs e) { // Use this event for the following: // Check the IsPostBack property to determine whether this is the first time the page is being processed. // Create or re-create dynamic controls. // Set a master page dynamically. // Set the Theme property dynamically. }

------------------------------------------------------------------------

(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Init(object sender, EventArgs e)

{// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.}

-------------------------------------------------------------------

(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_InitComplete(object sender, EventArgs e)

{ // Raised by the Page object. Use this event for processing tasks that require all initialization be complete. }

------------------------------------------------------------------------

(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance

(1)Loads ViewState : ViewState data are loaded to controls

Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.

(2)Loads Postback data : postback data are now handed to the page controls

Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreLoad(EventArgs e)

{ // Use this event if you need to perform processing on your page or control before the Load event. // Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.}

------------------------------------------------------------------------

(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_Load(object sender, EventArgs e)

{ // The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. // Use the OnLoad event method to set properties in controls and establish database connections.}

------------------------------------------------------------------------

(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file).

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Button1_Click(object sender, EventArgs e)

{ // This is just an example of control event.. Here it is button click event that caused the postback}

---------------------------------------------------------------------

(7)LoadComplete This event signals the end of Load.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_LoadComplete(object sender, EventArgs e)

{ // Use this event for tasks that require that all other controls on the page be loaded.}

----------------------------------------------------------------------

(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnPreRender(EventArgs e)

{ // Each data bound control whose DataSourceID property is set calls its DataBind method. // The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.}

-----------------------------------------------------------------------

(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected override void OnSaveStateComplete(EventArgs e)

{ // Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.}

------------------------------------------------------------------------

(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.

Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

// Render stage goes here. This is not an event

------------------------------------------------------------------------

(11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on-

(a)Instances of classes i.e. objects

(b)Closing opened files

(c)Closing database connections.

EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page

protected void Page_UnLoad(object sender, EventArgs e)

{ // This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections. // During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. //If you attempt to call a method such as the Response.Write method, the page will throw an exception. }

Design Patterns - Observer pattern

In this post we are going to take a look at the Observer pattern.
What Is The Observer Pattern?

The Observer pattern is a way for an object to notify all of it’s dependants when something changes based on a one to many relationship.
The Situation

Continuing to use our city dog registration software senario, one of the project’s requirements is that the dog’s owner’s be notified whenever a dog is processed for an infraction (i.e. picked up by the dog catcher). The Observer pattern is perfectly suited to solve this problem.
Setting Up Our Observer

First before we create our Observer we need to define some classes and interfaces that we will need to use with the Observer.
public interface IInfraction {
string Type { get; set; }
int Id { get; set; }
DateTime Date { get; set; }
string Reason { get; set; }
double Fee { get; set; }
}

public class Infraction : IInfraction {
public string Type { get; set; }

int Id { get; set; }

DateTime Date { get; set; }
string Reason { get; set; }
double Fee { get; set; }
}

public interface IOwner {
int Id { get; set; }

string FirstName { get; set; }

string LastName { get; set; }

string EmailAddress { get; set; }
}

public class Owner : IOwner {
public Owner() { }
public int Id { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public string EmailAddress { get; set; }

}

The above code defines an infraction and an owner for our Observer to use. Now we can setup our Observer and the notifications when a dog gets an infraction.
public interface IDog {
int Id { get; set; }
string Name { get; set; }
void AddInfraction(IInfraction infraction);
void AddOwner(IOwner owner);
}

public class Dog : IDog {
private IList _owners;
private IList _infractions;

public Dog() {
_owners = new List();
_infractions = new List();
}

public void AddOwner(IOwner owner) {
_owners.Add(owner);
}

public void AddInfraction(IInfraction infraction) {
_infractions.Add(infraction);

//notify owners of infraction : the Observer
foreach(IOwner owner in _owners) {
string message = “Dear ” + owner.FirstName + “,\n\n” +
“We are writing you to inform you that there has been an incident with your dog, “ +
this.Name + “, and that the city had to get involved.\n\n” +
“Your dog is being held at the city dog pound for the following reason: “ + infraction.Reason + “.” +
“You can pick them up anytime. There will be a fee of $” + infraction.Fee + ” applied.”;
MessageService.SendEmail(owner.EmailAddress, “cityhall@fictionalcity.com”, message);
}
}

public int Id { get; set; }
public string Name { get; set; }
}

You can see the this pattern at work in the AddInfraction method. Everytime this method is called an infraction is added to the dog’s record and all the owners are sent an email detailing the infraction and where to pick up their dog. It’s nice when you can structure your code to handle situations automatically, for you and your clients.

Design Patterns - Abstract factory pattern

What Is An Abstract Factory

An abstract factory contains a set of methods that create families of objects. For example you might have a DogFactory class that has various methods for creating different kinds of dogs like CreatePoodle, CreateBeagle, CreateGoldenRetriever, and CreateChocolateLab.
Abstract Class Versus Interface

Before we get too deep into this pattern it is important to note that an abstract class that has only abstract methods is the same as an interface. The benefit of using an abstract class comes when you want to implement functionality in the base class so each derived class doesn’t need to repeat it.

Let’s say you have the following interface.

public interface ICalculatable {
int Add(int num1, int num2);
int Multiply(int num1, int num2);
}

This is a very trivial example but it will be fine for this illustration. If both those methods are going to be the same for each instance of the interface it seems silly to keep repeating the code over and over. It would make more sense to create an abstract class with two non abstract methods so you don’t have to write the code for each instance.

public abstract class Calculatable {
public int Add(int num1, int num2) {
return num1 + num2;
}

public int Multiply(int num1, int num2) {
return num1 * num2;
}
}

Then you could create multiple concreate classes that inherit from the Calculatable abstract class and not have to write any code for the Add and Multiply methods.
Program Requirements

We’ll be continuing on with our fictional city council that has commissioned us to develop an application that lets them manage their yearly dog registrations. Since the application is all about managing dogs and their owners it makes sense to have a DogFactory class that will create the different breeds of dogs that will be stored in the application.

Our application will have a factory that creates different breeds of dogs and each dog breed will inherit from the IDog interface.
The Pattern

First we’ll setup our abstract factory class that will serve as our contract or interface for a concrete factory class.

public abstract class AbstractDogFactory {
public abstract Poodle CreatePoodle();
public abstract Beagle CreateBeagle();
public abstract GoldenRetriever CreateGoldenRetriever();
public abstract ChocolateLab CreateChocolateLab();
}

Then we create a conrete class of our factory contract.
public class DogFactory : AbstractDogFactory {

public DogFactory() { }

public overrride Poodle CreatePoodle() {
return new Poodle();
}

public overrride Beagle CreateBeagle() {
return new Beagle();
}

public overrride GoldenRetriever CreateGoldenRetriever() {
return new GoldenRetriever();
}

public overrride ChocolateLab CreateChocolateLab() {
return new ChocolateLab();
}
}

Now we have our factory in place it is very simple to use. Obviously the above implementation is very basic but it illustrates the point.

AbstractDogFactory dogFactory = new DogFactory();
Poodle mittens = dogFactory.CreatePoodle();
mittens.Name = “Mittens”;

Friday, May 6, 2011

Design Pattern- Decorator Pattern

Definition

The definition of the Decorator Pattern, according to Wikipedia, is:

“The decorator pattern can be used to make it possible to extend (decorate) the functionality of a class at runtime. This works by adding a new decorator class that wraps
the original class. This wrapping is typically achieved by passing the
original object as a parameter to the constructor of the decorator when
it is created. The decorator implements the new functionality, but for
functionality that is not new, the original (wrapped) class is used.
The decorating class must have the same interface as the original class.”
The Situation

Lets say you are assigned a project that a colleague was working on. Maybe this coworker has fallen ill or has decided to leave the company, for whatever reason, this is now your responsibility. Your manager hands the project off to you and explains the details of the project and the new features that are required.

The application is a dog registration program that your city is currently using to manage all annual dog registrations. The program has been deployed for nearly a year and now the city has decided that they would like to track when a dog gets picked up by the dog catcher. Based on this history, dogs that regularly get into trouble will cost more to register to offset the cost of employing the dog catcher.

Once you take a look at the code you discover that your coworker did not write any unit tests for this application. How will you know if your changes are going to introduce bugs into the existing features? Simple, you don’t. Without unit tests, the only way to determine if something gets broken is to manually fire up the UI and test each feature and all the possible combinations that feature may entail. Not something we want to do. That’s when the Decorator Pattern comes into play. It will allow us to wrap the new functionality around existing objects so that we do not disrupt the other code using the existing objects.
The Existing Code

The existing model looks like this.
internal interface IDog {
int Id { get; set; }
string Name { get; set; }
string Breed { get; set; }
string Address { get; set; }
DateTime RegisterDate { get; set; }
int RegistrationCost { get; }
}

public class Dog : IDog {
public Dog() : this(new DogRepository()) { }

public Dog(IRepository repository) {
_repository = repository;
}

private IRepository _repository;

private int id;
public int Id {
get { return id; }
set { id = value; }
}

private string name;
public string Name {
get { return name; }
set { name = value; }
}

private string breed;
public string Breed {
get { return breed; }
set { breed = value; }
}

private string address;
public string Address {
get { return address; }
set { address = value; }
}

private DateTime registerDate;
public DateTime RegisterDate {
get { return registerDate; }
set { registerDate = value; }
}

public int RegistrationCost {
get { return 25; }
}
}

This may not be the prettiest code but it is what it is. You can chalk that up to your coworker not being as good of a programmer as you or me just being lazy with the example code.
The New Requirements

So as mentioned above, the city now wants to track how often a dog is picked up by the dog catcher to determine if the registration cost for that dog should be higher. These details will be stored in a new database table called Infractions. The corresponding model class will look like this.
public class Infraction {
public Infraction() { }

private int id;
public int Id {
get { return id; }
set { id = value; }
}

private int dogId;
public int DogId {
get { return dogId; }
set { dogId = value; }
}

private string reason;
public string Reason {
get { return reason; }
set { reason = value; }
}

private DateTime infractionDate;
public DateTime InfractionDate {
get { return infractionDate; }
set { infractionDate = value; }
}
}
The Decorator Code

Now that we know our new requirements and have defined the structure of the new information we can get to work building our decorator. We’ll create an abstract class that implements the IDog interface.

public abstract class DogDecorator : IDog {
private IDog _dog;

public DogDecorator(IDog dog) {
_dog = dog;
}
}


Next we’ll create our decorator from the abstract class that will look up the infractions and calculate the new registration cost.


public class InfractingDog : DogDecorator {
public InfractingDog(IDog dog) :
this(dog, new DogRepository()) { }

public InfractingDog(IDog dog, IRepository repository) {

base(dog);
_repository = repository;
}

private IRepository _repository;

public int Id {
get { return _dog.Id; }
set { _dog.Id = value; }
}

public string Name {
get { return _dogName; }
set { _dog.Name = value; }
}

public string Breed {
get { return _dog.Breed; }
set { _dog.Breed = value; }
}

public string Address {
get { return _dog.Address; }
set { _dog.Address = value; }
}

public DateTime RegisterDate {
get { return _dog.RegisterDate; }
set { _dog.RegisterDate = value; }
}

public int RegistrationCost {
get {
IList<Infraction> infractions =
_repository.GetInfractionsByDogId(_dog.Id);

//increase registration by $5
//for every infraction
int extraCost = infractions.Count * 5;

return _dog.RegistrationCost + extraCost;
}
}
}
Final Thoughts

What we have done is wrap our original Dog class in a decorator to add new functionality. By doing it this way we don’t have to worry about breaking any old functionality because we didn’t change the original class. I hope this has demonstrated the Decorator Pattern to you in an easy to understand way that resembles a possible real world situation.