Pages

Apr 24, 2013

Asp.net Connection String Performance Optimization:



Asp.net Connection String Performance Optimization: 
 
Introduction:
   Most ADO.NET data providers use connection pooling to improve the performance of applications built around Microsoft's disconnected .NET architecture. An application opens a connection (or gets a connection handle from the pool), runs one or more queries, processes the row set, and releases the connection back to the pool. Without connection pooling, these applications would spend a lot of additional time opening and closing connections.
When you use ADO.NET connection pooling to manage connections for your Web-based applications and client/server Web service applications, your customers will usually get faster connections and better overall performance. But what happens when your application or Web site is suddenly flooded with customers who all want to connect at the same time? Will your applications sink or swim? Like a lifeguard, you need to monitor your connection pools carefully to maintain good performance and to prevent your pools from overflowing. Let's explore the reasons a connection pool might overflow, and then see how you can write code or use Windows Performance Monitor to monitor your pools.
These are ways to following the connection string in your application some of avoid the discomfort and increase performance better in your application.
     Your check status in your mssql server Process .we were open the connection data provider  .net framework using sqlserver means in display program name “.Net SqlClient Data Provider “   and  also display the waiting time .
 
SELECT SPID,STATUS,waittime,PROGRAM_NAME,LOGINAME=RTRIM(LOGINAME),HOSTNAME,CMD FROM  MASTER.DBO.SYSPROCESSES 
 
once the connectio open to exiting the process status by sleeping.



 
 
SELECT SPID,STATUS,waittime,PROGRAM_NAME,LOGINAME=RTRIM(LOGINAME),HOSTNAME,CMD FROM  MASTER.DBO.SYSPROCESSES where Status='runnable'
 
If you have to execute query using Sql query Editor to display status by runnable.
 
 
Otherwise to execute System Store procedure:
 
EXEC SP_WHO
 
 
 
Pooling:



Pooling Architecture:
 
 
Connection string pooling to Controlling properties:
1.      Pooling 
2.      Packet Size
3.      Min Pool Size
4.      Max Pool Size
5.      Connection Life Time 
6.      Connection Timeout 
7.      Enlist
8.      Increase the Pool Size
9.      Decrease the  Pool size
 
Sample Connection String Controlling pooling:
 
<add name="LocalSqlServer" connectionString="Data Source=************;Persist Security Info=True;User Id=****;Password=*******;Initial CataLog=*******;Trusted_Connection=False;Pooling=True;Max Pool size=100;Min pool size=0;Packet Size=512;Connection Timeout=0"  />
 
1. Pooling:
   
Introduction:
 
.net framework pages Connection through the database improving the performance to use and Polling Concept. A connection container of open the pool reusable connection. When the connection to open to use a pool memory .when last connection is closed the database other pool can used. The main disadvantage is that one or more database connections, even if they are currently not being used, are kept open. The Data Providers in ADO.NET have Connection Pooling turned on by default; if you need to turn it off, specify Pooling = false in the connection string being used. Connection Pooling gives you an idle, open, reusable connection instead of opening a new one every time a connection request to the database is made. When the connection is closed or disposed, it is returned to the pool and remains idle until a request for a new connection comes in. If we use Connection Pooling efficiently, opening and closing of connections to the database becomes less resource expensive. This article discusses what Connection Pooling is all about and how Connection Pooling can be used efficiently to boost the performance and scalability of applications.
 
The Default Pool is: Pooling=True;
 
When pooling to true. The SQLConnection object is drawn from the appropriate pool, or if it is required, is created and added to the appropriate pool to false.  
 
2. Packet Size:
 
The Default Packet Size is: Packet Size =512;
Packet Size may be a value in the range of 512 and 32767 bytes. An exception is generated if the value is outside this range.
Setting the default value to a number greater than 8000 will cause the packets to use the MultiPage allocator on the instance of SQL Server instead of the much more efficient SinglePage allocator, reducing the overall scalability of the SQL Server.
3. Minimum Pool Size:
 
    The Default Minimum Pool Size is: Min Pool Size =0;
 
   The minimum number of connections allowed in the pool.
 
4. Maximum Pool Size:
 
     The Default Maximum Pool Size is:  Max Pool Size=100;
     The Maximum Pool Size is depends upon the Server Configuration. The Maximum    number of Connection allowed in the pool configuration.
 
5. Connection Life Time:
The Default Connection Life time is:  Connection LifeTime =0;
 
When a connection is returned to the pool, its creation time is compared with the current time, and the connection is destroyed if that time seconds. The value specified by Connection Lifetime. A value of zero causes pooled connections to have the maximum connection timeout.
 
6. Connection Timeout:
 
The Default Connection TimeOut is:  Connection TimeOut =15;
 
Maximum Time (in secs) to wait for a free connection from the pool
 
7. Enlist:
 
The Default Enlist: Enlist=True;
 
When Enlist   true means Pooler automatically enlists the connection in the creation thread's current transaction context. Recognized values to use Set Enlist = "false" to ensure that connection is not context specific.
 
8. Increase the Pool Size:
 
The Default Increase pool size: Incr Pool Size=5;
 
Controls the number of connections that are established when all the connections are used.
 
9. Decrease the Pool size:
 
The Default Decrease pool size: Decr Pool Size=1;
 
Controls the number of connections that are closed when an excessive amount of established connections are unused.
 

 
 
 
 
 
 
 
 

Asp control Drag and Drop Gridview to Store DB Position



Asp control Grid view Drag And Drop And Save the Position:

Add Js File in your Application:

1.tabledndDemo.js

 
if(document.getElementById('txtGridNames')!=null) {
    debugger;
    var GridNames = document.getElementById('txtGridNames').value;
   
    var GridObj = GridNames.split('|'); 
    
    for (var i=0; i < GridObj.length; i++) 
    {
        var GObj = document.getElementById(GridObj[i])        
        var tableDrop = new TableDnD();
 
    tableDrop.findDropTargetRow = function(y) {
    var rows = this.table.tBodies[0].rows;    
         var debugStr = "y is "+y+"<br>";
    for (var i=1; i<rows.length; i++) {
        var row = rows[i];
        var rowY    = this.getPosition(row).y;
        var rowHeight = parseInt(row.offsetHeight)/2;
                 if (row.offsetHeight == 0) {
                          rowY = this.getPosition(row.firstChild).y;
                          rowHeight = parseInt(row.firstChild.offsetHeight)/2;
                 }                
                 debugStr += "row["+i+"] between "+(rowY-rowHeight)+' and '+(rowY+rowHeight)+"<br>";
        // Because we always have to insert before, we need to offset the height a bit
        if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
            // that's the row we're over
                          //document.getElementById('debug').innerHTML = debugStr+"found row";             
            return row;
        }
    }   
         //document.getElementById('debug').innerHTML = debugStr+"no matching row";
    return null;
}
// Redefine the onDrop so that we can display something
    tableDrop.onDrop = function(table, row)
    {
        var rows = this.table.tBodies[0].rows;              
             var debugStr = "rows now: ";
        for (var i=1; i<rows.length; i++) {
                 debugStr += rows[i].id+" ";
             }    
             //document.getElementById('debug').innerHTML = 'row['+row.id+'] dropped<br>'+debugStr;
             
             //Rearranging the SNO in Grid
             var rows_no = this.table.tBodies[0].rows;  
             
             for (var j=1; j<rows_no.length; j++)
             {
             
            var rowtr = rows_no[j];
            if (rowtr.cells[1])
            {
            rowtr.cells[1].innerHTML=j;
            if (table.id == "MainContent_gv_subordiantes")
            {
               if(j%2==0)
                   rowtr.style.backgroundColor = "#c7e6fc";
               else
                   rowtr.style.backgroundColor = "#FFFFFF";
            }
            else
            {
                if(j%2==0)
                    rowtr.style.backgroundColor="#FFFFFF";
                else
                    rowtr.style.backgroundColor = "#c7e6fc";
            }  
            }  
        }
     
         
     }
    tableDrop.init(GObj);
 }    
}
 
2.tablednd.js

// ===================================================================
// Author: Denis Howlett <feedback@isocra.com>
// WWW: http://www.isocra.com/
//
// NOTICE: You may use this code for any purpose, commercial or
// private, without any further permission from the author. You may
// remove this notice from your final code if you wish, however we
// would appreciate it if at least the web site address is kept.
//
// You may *NOT* re-distribute this code in any way except through its
// use. That means, you can include it in your product, or your web
// site, or any other form where the code is actually being used. You
// may not put the plain javascript up on your site for download or
// include it in your javascript libraries for download.
// If you wish to share this code with others, please just point them
// to the URL instead.
//
// Please DO NOT link directly to this .js files from your site. Copy
// the files to your server and use them there. Thank you.
// ===================================================================
 
/** Keep hold of the current table being dragged */
var currenttable = null;
 
/** Capture the onmousemove so that we can see if a row from the current
 *  table if any is being dragged.
 * @param ev the event (for Firefox and Safari, otherwise we use window.event for IE)
 */
document.onmousemove = function (ev) {
    
    if (currenttable && currenttable.dragObject) {
        ev = ev || window.event;
        var mousePos = currenttable.mouseCoords(ev);
        var y = mousePos.y - currenttable.mouseOffset.y;
        if (y != currenttable.oldY) {
            // work out if we're going up or down...
            var movingDown = y > currenttable.oldY;
            // update the old value
            currenttable.oldY = y;
            // update the style to show we're dragging
            //currenttable.dragObject.style.backgroundColor = 'transparent';
            // If we're over a row then move the dragged row to there so that the user sees the
            // effect dynamically
            var currentRow = currenttable.findDropTargetRow(y);
            if (currentRow) {
                if (movingDown && currenttable.dragObject != currentRow) {
                    currenttable.dragObject.parentNode.insertBefore(currenttable.dragObject, currentRow.nextSibling);
                } else if (!movingDown && currenttable.dragObject != currentRow) {
                    currenttable.dragObject.parentNode.insertBefore(currenttable.dragObject, currentRow);
                }
            }
        }
 
        return false;
    }
}
 
// Similarly for the mouseup
document.onmouseup   = function(ev){
    if (currenttable && currenttable.dragObject) {
        var droppedRow = currenttable.dragObject;
        // If we have a dragObject, then we need to release it,
        // The row will already have been moved to the right place so we just reset stuff
        //droppedRow.style.backgroundColor = 'transparent';
        currenttable.dragObject   = null;
        // And then call the onDrop method in case anyone wants to do any post processing
        currenttable.onDrop(currenttable.table, droppedRow);
        currenttable = null// let go of the table too
    }
}
 
 
/** get the source element from an event in a way that works for IE and Firefox and Safari
 * @param evt the source event for Firefox (but not IE--IE uses window.event) */
function getEventSource(evt) {
    if (window.event) {
        evt = window.event; // For IE
        return evt.srcElement;
    } else {
        return evt.target; // For Firefox
    }
}
 
/**
 * Encapsulate table Drag and Drop in a class. We'll have this as a Singleton
 * so we don't get scoping problems.
 */
function TableDnD() {
    /** Keep hold of the current drag object if any */
    this.dragObject = null;
    /** The current mouse offset */
    this.mouseOffset = null;
    /** The current table */
    this.table = null;
    /** Remember the old value of Y so that we don't do too much processing */
    this.oldY = 0;
 
    /** Initialise the drag and drop by capturing mouse move events */
    this.init = function(table) 
    {    
        this.table = table;
        if(table)
        {
        var rows = table.tBodies[0].rows; //getElementsByTagName("tr")        
        for (var i=1; i<rows.length; i++) 
        {
            //Pager row chkd here & background image not applied
            if(rows[i].cells.length!="1"){
            //To set Drag image for the dragging the rows   
             rows[i].cells[0].style.backgroundImage='url(../images/ReOrder.png)';
             rows[i].cells[0].style.backgroundRepeat="no-repeat";
             rows[i].cells[0].style.backgroundPosition="center";
            //End
           }
                          // John Tarr: added to ignore rows that I've added the NoDnD attribute to (Category and Header rows)
                          var nodrag = rows[i].getAttribute("NoDrag")
                          if (nodrag == null || nodrag == "undefined")
                          //There is no NoDnD attribute on rows I want to drag
                                   this.makeDraggable(rows[i]);
                          }
         }            
       }
    }
 
    /** This function is called when you drop a row, so redefine it in your code
        to do whatever you want, for example use Ajax to update the server */
    this.onDrop = function(table, droppedRow) {
        // Do nothing for now       
    }
 
         /** Get the position of an element by going up the DOM tree and adding up all the offsets */
    this.getPosition = function(e){
        var left = 0;
        var top  = 0;
                 /** Safari fix -- thanks to Luis Chato for this! */
                 if (e.offsetHeight == 0) {
                          /** Safari 2 doesn't correctly grab the offsetTop of a table row
                              this is detailed here:
                              http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari/
                              the solution is likewise noted there, grab the offset of a table cell in the row - the firstChild.
                              note that firefox will return a text node as a first child, so designing a more thorough
                              solution may need to take that into account, for now this seems to work in firefox, safari, ie */
                          e = e.firstChild; // a table cell
                 }
 
        while (e.offsetParent){
            left += e.offsetLeft;
            top  += e.offsetTop;
            e     = e.offsetParent;
        }
 
        left += e.offsetLeft;
        top  += e.offsetTop;
 
        return {x:left, y:top};
    }
 
         /** Get the mouse coordinates from the event (allowing for browser differences) */
    this.mouseCoords = function(ev){
        if(ev.pageX || ev.pageY){
            return {x:ev.pageX, y:ev.pageY};
        }
        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
            y:ev.clientY + document.body.scrollTop  - document.body.clientTop
        };
    }
 
         /** Given a target element and a mouse event, get the mouse offset from that element.
                 To do this we need the element's position and the mouse position */
    this.getMouseOffset = function(target, ev){
        ev = ev || window.event;
 
        var docPos    = this.getPosition(target);
        var mousePos  = this.mouseCoords(ev);
        return {x:mousePos.x - docPos.x, y:mousePos.y - docPos.y};
    }
 
         /** Take an item and add an onmousedown method so that we can make it draggable */
    this.makeDraggable = function(item) {
        if(!item) return;
        var self = this// Keep the context of the TableDnd inside the function
        item.onmousedown = function(ev) {
            // Need to check to see if we are an input or not, if we are an input, then
            // return true to allow normal processing
            var target = getEventSource(ev);
            if (target.tagName == 'INPUT' || target.tagName == 'SELECT'return true;
            currenttable = self;
            self.dragObject  = this;
            self.mouseOffset = self.getMouseOffset(this, ev);
            return false;
        }        
        item.style.cursor = "pointer";
    }
 
    /** We're only worried about the y position really, because we can only move rows up and down */
    this.findDropTargetRow = function(y) {
        var rows = this.table.tBodies[0].rows;        
                 for (var i=0; i<rows.length; i++) {
                          var row = rows[i];
                          // John Tarr added to ignore rows that I've added the NoDnD attribute to (Header rows)
                          var nodrop = row.getAttribute("NoDrop");
                          if (nodrop == null || nodrop == "undefined") {  //There is no NoDnD attribute on rows I want to drag
                                   var rowY    = this.getPosition(row).y;
                                   var rowHeight = parseInt(row.offsetHeight)/2;
                                   if (row.offsetHeight == 0) {
                                            rowY = this.getPosition(row.firstChild).y;
                                            rowHeight = parseInt(row.firstChild.offsetHeight)/2;
                                   }
                                   // Because we always have to insert before, we need to offset the height a bit
                                   if ((y > rowY - rowHeight) && (y < (rowY + rowHeight))) {
                                            // that's the row we're over
                                            return row;
                                   }
                          }
                 }
                 return null;
         }
}



Grid View control:
<input type="hidden" id="txtGridNames" value="MainContent_DG|MainContent_gv_subordiantes|" />
       <script type="text/javascript" language="javascript" src="Scripts/tablednd.js"></script>
                                                                                                         <asp:GridView ID="gv_subordiantes" SkinID="newskin_GridDoc" Width="80%" CssClass="hand" style="border:1px solid #B8CFE1;overflow:hidden;" EmptyDataText="No Records Found" runat="server" AllowSorting="True" AllowPaging="false" AutoGenerateColumns="False"  >
                                                                                                                    <AlternatingRowStyle BackColor="#c7e6fc" /> <RowStyle BackColor="White" HorizontalAlign="Left" /> <HeaderStyle HorizontalAlign="Left"   CssClass="GridHeaderLayoutview"/>
                                                                                                                      <Columns>
 <asp:TemplateField ItemStyle-CssClass="hand" HeaderText="Drag" HeaderStyle-Width="1%"><ItemStyle /><ItemTemplate></ItemTemplate></asp:TemplateField>
                                                          <asp:BoundField DataField="Employeeid" />
                                                          <asp:BoundField DataField="Lastname" />
                                                          <asp:BoundField DataField="Firstname" />
                                                          </Columns>
                                                          </asp:GridView>
                                                           <script type="text/javascript" language="javascript" src="Scripts/tabledndDemo.js"></script>

JavaScript: Save the Rearrange Value.
  function Save_sub() {
                   var Gv_sub = document.getElementById('gv_subordiantes');
                   this.table = Gv_sub; var row_no = Gv_sub.tBodies[0].rows;
                   var _value = ""var id = "";
                   for (var j = 1; j < row_no.length; j++) {
                            var rowtr = row_no[j];
                            if (rowtr.cells[0].childNodes[0].value == "") {
                                     id = rowtr.cells[2].childNodes[0].value;
                            } else {
                                     id = rowtr.cells[0].childNodes[0].value;
                            }
                            document.getElementById('<%=hidPosition.ClientID%>').value += id + "|" + rowtr.cells[1].innerHTML + ",";
                            _value += id + "|" + rowtr.cells[1].innerHTML + ",";
                   }
                   __doPostBack('SubMenu''EmpSave');
           }



server Side Coding:

if (Request.Form["__EventArgument"].ToString() == "EmpSave")
                        {
 Save_emp();

}

private void   Save_emp()
    {
       // int _splitval = Convert.ToInt32(Hdn_imgdelid.Value);
        string StrSql1 = "";
        if (hidPosition1.Value != "" && hidPosition1.Value != null)
        {           
                string StrSql = "";
                string[] _Split = hidPosition1.Value.Split(',');
                for (int i = 0; i < _Split.Length - 1; i++)
                {
                    string[] _position = _Split[i].ToString().Split('|');
                    StrSql += " update Performance_LegoMetrics set position='" + _position[1] + "' where LegoMetricsId='" + _position[0] + "' ";
                    // StrSql += " update performance_pulledmetrics set position='" + _position[1] + "' where LegoMetricsId='" + _position[0] + "' ";
 
                }
}
}