Tuesday, 3 April 2018

008 ADO.Net Connection Pooling


Connection pooling

                  An application connect to database with the help of connection. Creating a connection is  high resource consuming process .To establish a connection , a connection string is required , which is either from machine.config or web.config  or from hard coded string . To create a connection , a physical socket channel  or named pipe is established, handshaking between client and server occurred.

                      Ado.Net architecture is disconnected in nature, web application frequently fires sql query to the database for data manipulation. Each time a query is fire, physical connection is required to execute this query. To establish connection each time, performance of the web application degraded and make quality of the application poor.

                      To speed up the process , connection pool is used. Connection pool is a technique to  reuse existing connection. The pool maintain the ownership of the physical connection. When a connection is free,  it is keep in a connection pool and make the connection alive. When the next  connection is ask,  connection pool first check, if there is any available connection  in the pool . If there is available connection in the pool, connection is assign from the pool else a new connection is established.

                      Connection pooling  reduce the number of times new connection open, increase  performance and scalability of the application.

                        Connection pool remove when ISS  reset or application domain unloaded.
Another option is  ClearAllPools and ClearPool  to clear the connection for a given provider and for a specific connection respectively.

 Here are some points related to the connection pooling
* If you want to pull a set of connection, the connection string must be same.
* Security context of each connection must be same.
* All connection must be comes under the same process.

Below is the example of connection pool

Example 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class Default2 : System.Web.UI.Page
{
           protected void Page_Load(object sender, EventArgs e)
           {
                  string sqlConnectString = "Data Source= xxx.xxx.xxx.xxx; initial catalog=MyDatabaseName;Connect Timeout=6000; User ID=MyUserID;Password=MyPassword";

                 SqlConnection connection = new SqlConnection();

                 connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection  Lifetime=0;Min Pool Size=0;Max Pool Size=100;Pooling=true;";

                connection.Open();

                //for command executing
                SqlCommand cmd = new SqlCommand("select * from tbl_myTable");

               cmd.Connection = connection;
               SqlDataReader dr = cmd.ExecuteReader();

              //for data set
               SqlDataAdapter da = new SqlDataAdapter("select * from tbl_myTable", connection);


        }
}


You can control the connection pool by the help of this property

MaxPoolSize : Maximum number of connection is allowed in the pool.Default value is 100
MinPoolSize : Minimum number of full allowed in the connection pool. Default value is 0.
Pooling: Boolean value true or false. when true  connection is drawn from pooling.
Connection Timeout:  Maximum number of second to wait  for a connection to be established. The default value is 15.
Incr Pool Size  : Number of connection to be established when all connection are in use. The default value is 5.

How a connection pool can be visible. Connection pool can be visible  in the SQL server.
Exec sp_who / sp_who2 stored procedure return  result that number of connection is there in the database . You can also monitor  connection pooling performance from SQL profiler also.


Example 1

SELECT  DB_NAME(dbid) as Data_Base_Name,
                COUNT(dbid) as Number_Of_Connections,
                loginame as Login_uSER_Name 
 
        FROM   sys.sysprocesses  

WHERE dbid
GROUP BY dbid, loginame

Output
Result
----------------------------------------
database1    3            user1

database2    4            user1 

017 Asp.Net Adrotator

Adrotator

Adrotator is a  server site  control introducing Asp.Net. Adrotator display advertisement dynamically. Adrotator is not static, if there are more advertisement, advertisement comes one by one , when a page is postback . Adrotator display image with text, when click on Adrotator . Adrotator  redirect URL to the advertisers WebSite . It is a server side control simply  in use , it read XML file  to display advertisement. The XML has a specific format which can be read by  Adrotator.

Here is the most common attribute of the  Adrotator. 
  • Constructor : 
  1. Adrotator : Create a new instance of  adrotator. 
  •  Properties 
  1. BackColor : Get or Set background color of a adrotator. 
  2. BorderColor : Get or Set border color of a adrotator. 
  3. BorderStyle : Get or Set border style of a adrotator. 
  4. BorderWidth : Get or Set border with offer ad adrotator. 
  5. ClientID : Get the ID generated by server  in HTML ,to identify the control. 
  6. CssClass : Get or Set CSS class of the adrotator. 
  7. Enabled : Get or Set adrotator enabled /disabled , boolean indicator true or false. 
  8. ForeColor :  Get or Set fore color of the adrotator. 
 
  • Method 
  1. Databind  : Bind data with the data source .
  2. Findcontrol :Search for a server control with parameter to identify that control.

  • Event
  1. Disposed : Dispose the advertisement and release all the memories.
  2. Load : Raised event when control is load.
  3. Prerender : Raised event before control is render.
  4. AdCreated : Raised event when advetisement is created.

Adrotator work with particular XML format, the schema of the XML file content all information and URL link related to advertisement.

Below is the explanation of the XML tag

<  Ad > Starting Tag of an advetisement.
< ImageUrl >  The URL of the image source on advertisement display.
< NavigateUrl >  When click on the advertisement , user will be navigate to this URL.
< AlternateText >  A text to display on the tooltips , when user take is mouse on the advertisement.
< Keyword >  String to filter advertisement category.
<  Impressions > How many user like that advertisement.
< Caption >  Caption of the advertisement.

 Below is a XML file. Pillow is the example of the ad rotator with the help of the XML file.


XML File
xml version="1.0" encoding="utf-8" ?>
<Advertisements>
<Ad>
<ImageUrl>Demo1.png</ImageUrl>
<NavigateUrl>http://google.com</NavigateUrl>
<AlternateText>Advertisement of C# Course </AlternateText>
<Impressions>95</Impressions>
</Ad>
<Ad>
<ImageUrl>Demo2.png</ImageUrl>
<NavigateUrl>http://yahoo.com</NavigateUrl>
<AlternateText>Advertisement of Asp.Net Course</AlternateText>
<Impressions>54</Impressions>
</Ad>
<Ad>
<ImageUrl>Demo3.png</ImageUrl>
<NavigateUrl>http://bing.com</NavigateUrl>
<AlternateText>Advertisement of Sql Server</AlternateText>
<Impressions>554</Impressions>
</Ad>
</Advertisements>

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableViewState="false" %>
<%@ OutputCache Duration="60" VaryByParam="DropDownList1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
         <body>
                     <form id="form1" runat="server">
                             <div>
                                     <asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/XMLFile.xml" />
                     </div>
                   </form>
         </body>
</html>

Default.aspx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
         protected void Page_Load(object sender, EventArgs e)
         {
         }
}


Output

009 ADO.Net Transaction Processing

ADO.NET transaction processing

                    ADO.NET  allow us a group of command  to be  executed in against a single connection. Consider the situation when  all command , need to be executed successfully or ,if  any  error occure during any command execution, all transaction need to be rolled back . Not a single  record mismatch can be happen. 


                               ADO.NET transaction processing is very useful for real life use of software. For example Banking software, Ticket booking software etc.For Ticket booking software , first step to make payment , 2nd step  to book a ticket. There are two stage to book a ticket. Ticket booking will be complete if two step completed successfully. Payment is made but ticket is not booked make a System Wrong. Transaction processing allowed only commit data when both successful. 

ADO.NET transaction processing follow ACID property. 

Atomic : The whole transaction is considered as a single work , atomic unit of processing,either  perform or not perform at all. 

Consistency : Data relation ship is maintained correctly. No data can be insert , update, delete breaking the data relationship rule. 

Isolation : Transaction should not make update visible two other client , until committed. 

Durability : Once a change is made, it is permanent. 


Step of do a transaction processing

1) Create a instance of a connection .
2) Open  connection .
3) Create instance of a transaction .
4) Create a command and execute against transaction .
5) Repeat the step (4) if there is more command .
6) If all command execution success, then commit transaction.
7) If any command get error, rollback the transaction.
8)Close connection.

Example 1 (A simple Transaction Processing)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
        class Program
        {
                 static void Main(string[] args)
                 {
                          string conString = "Your Conncetion String ";
                          SqlConnection con = new SqlConnection(conString);
                          SqlTransaction trans;
                          con.Open();
                          trans = con.BeginTransaction();

                          try
                              {
                                      new SqlCommand("INSERT INTO tbl_student(Name,Roll,Class) " +
                                                                 "VALUES('Student22',123,2);", con, trans)
                                    .ExecuteNonQuery();

                                     trans.Commit();
                              }
                             catch (SqlException sqlError)
                             {
                                       trans.Rollback();
                             }
                           con.Close();
                 }
         }
}



Different kind of isolation level can be applicable during the transaction processing. Isolation level is how  database current changes handheld. 

ReadUncommitted : In this kind of associate level, uncommitted data can be read, this is termed as  dirty read. 

ReadCommitted : This kind of isolation level,  prevent reading data before committed. But does not prevent  record from insert, update, delete  from other clients. This is the default isolation of a ADO.NET transaction processing. 

Chaos : It is similar like read uncommitted. But it consider the pending transaction while writing the in the  database.It make sure that different transaction is not overwritten.

RepeatableRead :  Lock read till the transaction is completed . 

Serializable : Lock entire DatSet being read till the transaction is completed.

Transaction processing is important in the application where  multiple client may try to change the database at the same time. With the growing of client , the situation will be worse and
worse .

Web application work on internet, it is not guaranteed that internet will be always available, unavailability of internet may occur error during a transaction  also. 

There is a chance that during on transaction a client close this application in between. 

There are several such reason  where an application experience exception during data processing. Transaction processing ensure  to overcome  this kind of problem. 

                             Sometimes an application is distributed, multiple server and multiple database, database need to be synchronized among them. For a large real time application , distributed application is necessary. To handle transaction processing on this kind of system,  
System.EnterpriseServices  namespace is used.

Example 2(A Transaction Processing with multiple command)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
      class Program
     {
           static void Main(string[] args)
             {
                      string conString = "You Connection String";
                      SqlConnection con = new SqlConnection(conString);
                      SqlTransaction trans;
                      con.Open();
                      trans = con.BeginTransaction();

                      try
                     {
                          new SqlCommand("INSERT INTO tbl_student(Name,Roll,Class) " +
                          "VALUES('Student15',123,2);", con, trans)
                        .ExecuteNonQuery();

                        new SqlCommand("INSERT INTO tbl_student(Name,Roll,Class) " +
                       "VALUES('Student16',123,2);", con, trans)
                     .ExecuteNonQuery();

                     new SqlCommand("INSERT INTO tbl_student(Name,Roll,Class) " +
                     "VALUES('Student16',123,2);", con, trans)
                    .ExecuteNonQuery();

                    new SqlCommand("INSERT INTO tbl_student(Name,Roll,Class) " +
                   "VALUES('Student17',123,2);", con, trans)
                   .ExecuteNonQuery();

                    trans.Commit();
                   Console.WriteLine("All Data Inserted and Commiter Sucessfully");
                }
               catch (SqlException sqlError)
               {
                    trans.Rollback();
                    Console.WriteLine("Error Occured !! Transaction have been roll backed");
               }
              con.Close();
             }
       }
}

Output 
All Data Inserted and Commiter Sucessfully

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...