Sunday, 26 August 2012

Reflection in C# / MS.NET


Reflection

1        The classes in the System.Reflection namespace, together with System.Type, allows us to obtain information about loaded assemblies and the types defined within them, such as classes, interfaces, and value types.

2        For a given class, using reflection we can query the list of all

a.       Constructors

b.      Methods

c.       Properties

d.      Fields

e.      Events

Note: This information is actually fetched from the Type Metadata and Assembly manifest of an assembly.

 

Following example demonstrates the usage of Reflection API to extract the details as needed.

using System.Reflection

//Sample Class.

class Demo

{

    internal void Bar()

    { }

    public void Foo(int a, string s)

    {

        Console.Write(a + " " + s);

    }

    public int Field1;

    public int Property1

    {

        get

        {

            return Field1;

        }

        set

        {

            Field1 = value;

        }

    }

}

 

static class Program

{

    static void Main()

    {

        Assembly objAssembly = Assembly.Load("mscorlib,2.0.0.0,Neutral,b77a5c561934e089");

        Type[] Types = objAssembly.GetTypes();

 

        // Display all the types contained in the specified assembly.

        foreach (Type objType in Types)

            Console.WriteLine(objType.Name.ToString());

 

        Type tp = typeof(Demo);

 

        //To get the list of all fields of a class.

        foreach (FieldInfo fi in tp.GetFields())

            Console.WriteLine(fi.Name);

 

        //To get the list of all properties of a class.

        foreach (PropertyInfo pi in tp.GetProperties())

            Console.WriteLine(pi.Name);

 

        //To get the list of all methods of a class.

        foreach (MethodInfo mi in tp.GetMethods(BindingFlags.NonPublic))

            Console.WriteLine(mi.Name + " " + mi.GetParameters().Length);

 

        //To create the instance of the class without using “new” operator

        Object ob = Activator.CreateInstance(tp);

 

        //ob.Foo(1, "A"); - Invalid

       

        //Following is equivalent of LateBinding of VB.NET 

        MethodInfo miFoo = tp.GetMethod("Foo");

        object[] arArgs = { 1, "A" };

        miFoo.Invoke(ob, arArgs); //Method Foo is Invoked

    }

}

 

Reflection is ideally used

1.       Building IDE applications like VS.NET

2.       Type browsers

3.       Common code which works on all types.

4.       In serialization, Reflection is used to get all the data of an object which has to be persisted.

 
Thanks for reading this article and I am sure you have understood the same with simple example.

Sunday, 19 August 2012

HTTP Protocol


HTTP Protocol


  • The communication between web server and web browser on internet is done using HTTP protocol.
  • HTTP is an application level protocol.
  • HTTP is a specification by IETF (Internet Engineering Task Force).
  • HTTP Protocol is the safest protocol on internet.
  • HTTP is a stateless protocol. This is because it doesn’t know whether the request that has been made is part of an ongoing correspondence or just a single message.
  • HTTP communicates only in the String Format and is thus virus free and is platform independent.
  • HTTP protocol works on PULL technology. i.e. we can pull everything available on webserver but we cannot push content to the server unless server allows for it.

HTTP Protocol supports following Methods
1. GET
2. POT
3. PUT
4. OPTIONS
5. DELETE
6. TRACE
7. CONNECT

Of all these the most commonly used methods are "POST" and "GET"

<form name="Form1" action="demo.asp" method="post" >
                <input type="…..
                <input type="submit" name="s1" value="Submit">
</form>

When the form is submitted by clicking on the submit button it submits the Name/ Value pair of every input element in the form to the server.

Difference between GET and POST Methods:

GET Method:
  1. All the name value pairs are submitted as a query string.
  2. It’s not secured as it is visible in plain text format in the Location bar of the web browser..
  3. Length of the data submitted to server is restricted.
  4. If method is not mentioned in the Form tag, this is the default method used.
  5. If get method is used and if the page is refreshed it would not prompt before the request is submitted again.
POST Method:
  1. All the name value paris are submitted in the Message Body of the request.
  2. Length of the string (amount of data submitted) is not restricted.
  3. Post Method is secured because Name-Value pairs cannot be seen in location bar of the web browser.
  4. If post method is used and if the page is refreshed it would prompt before the request is submitted again.
In simple words, if the sumitted data changes the state of server then POST should be used otherwsie GET must be used.

For Example:
Search criteria must always be submitted using GET method because the result of search doesn't make any change to server
but if the form is like Polling for something, then it must be POST method because this will change the data on server.

You can learn more from following FREE video
http://www.bestdotnettraining.com/VideoLibrary
Please expand ASP.NET and visit Web Programming Introduciton Chapter.

Sunday, 12 August 2012

MS.NET Specially C# Coding Standards


Naming convention's to be followed while programming in Visual Studio.NET

Declaration
Casing To be Used
Preferences
Namespace
Pascal Casing
Class
Pascal Casing
Enumerator Types
Pascal Casing
Enumerator Values
Pascal Casing
Interface
Pascal Casing
Always start with “I”
Exception Classes
Pascal Casing
Always end with “Exception”
Public Fields
Pascal Casing
Protected Fields
camel Casing
Private Fields
camel Casing
Start with _(Underscore)
Methods
Pascal Casing
Property
Pascal Casing
Parameter of Method
camel Casing
Static Member
Pascal Casing
Event
Pascal Casing
Delegate
Pascal Casing
Constant Variable
Upper Casing

Note:
In Pascal Casing – First character of the identifier will be in upper case and in the same identifier a new word should again begin with uppercase.
Eg: HelloApp, NameOfVariable

In camel Casing – First character is always lowercase and rest is same as Pascal casing.

Commenting Style
Every user defined classes, interfaces, enumerators and Methods should have following comments above them.

Purpose:
Created on:
Created by:
Modified on:
Modified by:
Status: Completed (InCompleted \Completed \Tested \Used)
public void Foo()
{ . . . }


INDENTATION and SPACES
Wrapping Lines
When an expression will not fit on a single line, break it up according to these general principles:
·         Break after a comma.
·         Break after an operator.
·         Prefer higher-level breaks to lower-level breaks.
·         Align the new line with the beginning of the expression at the same level on the previous line

White Spaces
Don't use spaces for indentation - use tabs!

Class and Interface Declaration
·         When coding C# classes and interfaces, the following formatting rules should be followed:
·         No space between a method name and the parenthesis "(" starting its parameter list.
·         The opening brace "{" appears in the next line after the declaration statement.
·         The closing brace " }" starts a line by itself indented to match its corresponding opening braces

Blank Lines
Blank lines improve readability. They set off blocks of code which are in themselves logically related.

Two blank lines should always be used between:
·         Logical sections of a source file
·         Class and interface definitions (try one class/interface per file to prevent this case)

One blank line should always be used between:
·         Methods
·         Properties
·         Local variables in a method and its first statement
·         Logical sections inside a method to improve readability

Note that blank lines must be indented as they would contain a statement this makes insertion in these lines much easier

Single spaces surround operators (except unary operators like increment or logical not),
Example: a = b; // don't use a=b;


Thankyou and Wishing You MOST and MORE successful career ahead.

Sunday, 5 August 2012

What is Connection Pooling in ADO.NET


When we want a front-end to communicate with database, we need to establish connections between them.

For this:
1. Database server has to create a socket and wait for the request to come.
2. Client will have to create a socket in its own process.
3. Client using its socket has to submit a request to server socket.
4. Sever socket should receive the request on existing client and shift’s the client to another new socket which has to be created freshly. This is done so that server main socket is free to receive request from another client(s).
5. Server will have to parse the connection string and authenticate the client
6. Server will then send an acknowledgement to the client that its connection is accepted.
7. Now both client and server are connected and they are ready for data exchange.

I am sure from the above you have understood that it is time taking process and to avoid this developers used to write code to Open the database connection in the beginning of the application and keep it open till the end. This has obvious drawback of keeping the resources blocked though are not in use, what I mean is if the application is running for let say one hour it doesn’t mean that all the time continuously it would keep fetching or updating data from the database though the connection to the database might remain open. At the same time it’s not recommended to Open the connection use it and then immediately close it because opening every time has the above mentioned cost (7 steps) and would also degrade the performance of the application.

In Windows based application, this is not really a very big concern because every client will be running its own copy of the application and thus a global variable can manage the single connection and same can shared by all the code running in that instance of the application.

Big concern is in Web Based applications (which are stateless) where on a single Web Server receives the requests from different browser based clients it will be executing the same code and will be using the same connection string to connect to the same database. Basically what I mean is many identical connections will have to be repeatedly opened and closed for every request and this would be a costly affair.

To minimize the overhead of Opening the connection every time it is required, ADO.NET uses the technique of Connection Pooling.

What is Connection Pool?
Connection Pool is a buffer in memory where the Managed Provider is going to keep all the physical connections to the database having the same connection string.
Note: For every different value of ConnectionString and for every Windows Identity (if Integrated Security is used) a new Connection Pool is created. Only when two Connection objects use the same connection string, they would use the same pool.

Customizing Connection Pooling:
It can be done by setting following key value pairs in ConnectionString property of connection object.


a. Pooling: True to enabling and False to disable connection pooling. Default is True.
b. Max Pool Size: Max number of connections allowed in the pool. Default value of this is 100
c. Min Pool Size: Number of connections which must be created when the Pool is created. Default is 0.

What happens if Pooling is enabled?
When connection pooling is enabled in the connection string and we try to open the connection, first the connection object will search the connection in the pool. If it finds a free connection in the pool, it uses the same but if either the pool is empty or all the connections in the pool are already in use then a new physical connection is established. This way the time required for opening the connection to the database is reduced and this will improve the performance of the application.

The care the developer has to take is, after opening the connection and performing the database operation the Close method of the connection object must be called immediately. Close method actually doesn’t really close the physical socket connection between client and database but will return the connection to the pool so that it’s then available to another connection object with in the same application/process

When are connections removed from the PoolConnection in the pool are actually closed/removed only when they are not used for a long period of time or for some reason the socket breaks the connection with the server (its marked as invalid by ADO.NET)

SqlConnection.ClearPool: Empties the connection pool associated with the specified connection.


Let’s understand connection pooling with an example. – Please read the comments provided with every statement.
class Program
{

static voidMain(string[] args)

{

SqlConnection c1,c2,c3,c4,c5;

c1 = new SqlConnection("server=.\\sqlexpress;database=db1;integrated security=true");

c2 = new SqlConnection("server=.\\sqlexpress;database=db2;integrated security=true");

c3 = new SqlConnection("server=.\\sqlexpress;database=db1;integrated security=true");

c4 = new SqlConnection("server=.\\sqlexpress;database=db1;integrated security=true");

c5 = new SqlConnection("server=.\\sqlexpress;database=db1;uid=sa;pwd=ss");

c1.Open(); //Pool 1 is created, a new connection is established

c2.Open(); //Pool2 is created, a new connection is established because database name is different

c3.Open(); //Pool1 is used but a new connection is established because c1 is not yet closed

c1.Close(); //Connection is returned to the pool and marked as free.

c4.Open(); //Pool1 is used and the Free connection released in previous statement is used.

c5.Open(); //Pool3 is created because authentication information is different.

c2.Close();

c3.Close();

c4.Close();

c5.Close();

}

}

Scenario 1:
Following code will create only one connection in the Pool and same connection is used by all the 100 connection objects.
SqlConnection [] connections = new SqlConnection[100];
for (int i = 0; i < connections.Length ; i++)
{
connections[i] = new SqlConnection("server=.\\sqlexpress;database=db1;integrated security=true");
connections[i].Open();
//...
connections[i].Close();
} 

Scenario 2:
Following code will create only 100 connection objects and 100 connections will be created in the Pool because we are not closing the connections
SqlConnection [] connections = new SqlConnection[100];
for (int i = 0; i < connections.Length ; i++)
{
connections[i] = new SqlConnection("server=.\\sqlexpress;database=db1;integrated Security=true");
connections[i].Open();
//...
}

Scenario 3:
Following code will throw runtime exception in 101th iteration because 100 connections are opened and not closed in for loop.
SqlConnection [] connections = new SqlConnection[101];
for (int i = 0; i < connections.Length ; i++)
{
connections[i] = new SqlConnection("server=.\\sqlexpress;database=db1;integrated security=true");
connections[i].Open();
//...
}

Thankyou.
Please don't forget to leave your comment if this has helped you to understand Connection Pooling in simplest language.