Saturday, October 13, 2007

Search

Monday, April 09, 2007

Connection Pooling in ASP.NET


Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections. When a new connection is requested , pool manager checks if the pool contains any unused connections and returns connection if available.


If all connections in the pool are busy and the maximum pool size has not been reached, then new connection is created and added to the pool. When the pool reaches its maximum size all new connection requests are being queued up until a connection in the pool becomes available or the connection attempt times out.

These are four parameters that control most of the connection pooling behavior
  • Max Pool Size - the maximum size of your connection pool. Default is 100

  • Min Pool Size - initial number of connections which will be added to the pool upon its creation. Default is zero

  • Connect Timeout - controls the wait period in seconds when a new connection is requested, if this timeout expires, an exception will be thrown. Default is 15 seconds.

  • Pooling - controls if your connection pooling on or off. Default as you may've guessed is true. Read on to see when you may use Pooling=false setting.

eg.

connstring="server=myserver;database;abcdefg;Min pool size=5;Max pool size=100;connection timeout=15;pooling=yes"

Most of the Connection problems are because of Connection Leaks

SqlConnection conn=new SqlConnection(constring);
conn.Open();
//do some thing
conn.Close();

while executing the functionality if Exception occurences, then for sure connection wont be closed , to close connection explicitly .. the simple way is ..

SqlConnection conn=new SqlConnection(constring);

try{
conn.Open();
//do some thing
}
finally()
{
conn.Close();
}


Saturday, February 17, 2007

Sorting Programs

Bubble Sort

Bubble sort is the simplest sorting technique . Unfortunately, the slowest also :).

Here is the sample source code for bubble sort

void bubbleSort(int numbers[], int array_size)
{
int i, j, temp;

for (i = (array_size - 1); i >= 0; i--)
{
for (j = 1; j <= i; j++) { if (numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
}



Insertion Sort

As name suggest , it inserts each item into its proper place in the final list, not suitable for larger lists

void insertionSort(int numbers[], int array_size)
{
int i, j, index;

for (i=1; i < index =" numbers[i];" j =" i;">while ((j > 0) && (numbers[j-1] > index))
{
numbers[j] = numbers[j-1];
j = j - 1;
}
numbers[j] = index;
}
}

Heap Sort
Slowest but recommended sorting technique for larger volumes of data
void heapSort(int numbers[], int array_size)
{
int i, temp;

for (i = (array_size / 2)-1; i >= 0; i--)
siftDown(numbers, i, array_size);

for (i = array_size-1; i >= 1; i--)
{
temp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = temp;
siftDown(numbers, 0, i-1);
}
}


void siftDown(int numbers[], int root, int bottom)
{
int done, maxChild, temp;

done = 0;
while ((root*2 <= bottom) &&amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp;amp; (!done)) { if (root*2 == bottom)
maxChild = root * 2;
else if (numbers[root * 2] > numbers[root * 2 + 1])
maxChild = root * 2;
else
maxChild = root * 2 + 1;

if (numbers[root] < temp =" numbers[root];" root =" maxChild;">else
done = 1;
}
}

Merge Sort
Splits the list into two ,sorts recursively and merged back final sorted list Faster than Heap Sort but required double the memory of Heap sort becoz of its 2nd array

void mergeSort(int numbers[], int temp[], int array_size
{
m_sort(numbers, temp, 0, array_size - 1);
}


void m_sort(int numbers[], int temp[], int left, int right)
{
int mid;

if (right > left)
{
mid = (right + left) / 2;
m_sort(numbers, temp, left, mid);
m_sort(numbers, temp, mid+1, right);

merge(numbers, temp, left, mid+1, right);
}
}

void merge(int numbers[], int temp[], int left, int mid, int right)
{
int i, left_end, num_elements, tmp_pos;

left_end = mid - 1;
tmp_pos = left;
num_elements = right - left + 1;

while ((left <= left_end) && (mid <= right)) { if (numbers[left] <= numbers[mid]) { temp[tmp_pos] = numbers[left]; tmp_pos = tmp_pos + 1; left = left +1; } else
{
temp[tmp_pos] = numbers[mid];
tmp_pos = tmp_pos + 1;
mid = mid + 1;
}
}

while (left <= left_end) { temp[tmp_pos] = numbers[left]; left = left + 1; tmp_pos = tmp_pos + 1; } while (mid <= right) { temp[tmp_pos] = numbers[mid]; mid = mid + 1; tmp_pos = tmp_pos + 1; } for (i=0; i <= num_elements; i++) { numbers[right] = temp[right]; right = right - 1; } }


Quick Sort

Quick sort algorithm is simple in theory,but very difficult to put into code.

Very fast Sorting Technique but Complex Algorithm Have a look

void quickSort(int numbers[], int array_size)
{
q_sort(numbers, 0, array_size - 1);
}


void q_sort(int numbers[], int left, int right)
{
int pivot, l_hold, r_hold;

l_hold = left;
r_hold = right;
pivot = numbers[left];
while (left <>while ((numbers[right] >= pivot) && (left <>if (left != right)
{
numbers[left] = numbers[right];
left++;
}
while ((numbers[left] <= pivot) && (left <>if (left != right)
{
numbers[right] = numbers[left];
right--;
}
}
numbers[left] = pivot;
pivot = left;
left = l_hold;
right = r_hold;
if (left <>if (right > pivot)
q_sort(numbers, pivot+1, right);
}

Selection Sort

simple and easy to implement but not recommended for larger lists

void selectionSort(int numbers[], int array_size)
{
int i, j;
int min, temp;

for (i = 0; i < min =" i;">for (j = i+1; j <>if (numbers[j] < min =" j;" temp =" numbers[i];">

Xml in .NET

The XML types are live in System.XML namespace

1. Import System.XML like

using System.XML // now we are ready to use xml in .net

2. we have two core abstract classes in XML.NET XmlReader and XmlWriter

XmlReader : Fast,read-only and Forward only cursor for processing xml documents
Xml Writer : Alows to produce xml documents with W3C's XML 1.0 + Namespaces Rcommendations

These two are inexpensive in memory cache which makes as alternatives to the classic DOM approach

How to Read XML Document in XML.NET ?
Reading xml document with XmlReader class , here is the example

public void ReadDocument(XmlReader reader)
{

while (reader.Read())
{
// Points to the Current Node of the Xml Document
String name = (reader.NodeType == XmlNodeType.Element ||
reader.NodeType == XmlNodeType.EndElement) ?
reader.NamespaceURI + "#" + reader.Name : reader.Name;
Console.WriteLine(name);
}
}


How to Write into XML Document in XML.NET


public void WriteDocument()
{
XmlWriter writer = new XmlTextWriter(Server.MapPath("test.xml"), null);
writer.WriteStartDocument();
writer.WriteComment("This is a sample comment");
writer.WriteStartElement("Carworld");
writer.WriteStartElement("name", "");
writer.WriteString("Maruthi");
writer.WriteEndElement();
writer.WriteStartElement("name", "");
writer.WriteString("Hyundai");
writer.WriteEndElement();
writer.WriteStartElement("name", "");
writer.WriteString("Daewoo");
writer.WriteEndElement();
writer.WriteEndElement();


writer.WriteEndDocument();

writer.Close();

}

How to Read or write with XmlDocument ?


1. assaign the xml file to XmlDocument object with Load method
2. Start from the Root Element and Display the XmlNode details
3.Check if that Node contains Child Nodes if so process them too ..

public void ReadXmlDocument()
{
string fname = "test.xml";
try
{
// Load the XML from file
XmlDocument myDoc = new XmlDocument();
myDoc.Load(Server.MapPath(fname));
// Process the supplied XML file
ProcessXmlFile(myDoc.DocumentElement);
}
catch (Exception e)
{
Response.Write(ex.Message());
}
}

public void ProcessXmlFile(XmlNode node)
{
if (node != null)
Response.Write(" Node Name :: + "+node.Name +" --> Node Value :: "+node.Value+"<br>");

if (node.HasChildNodes)
{
node = node.FirstChild;
while (node != null)
{
ProcessXmlFile(node);
node = node.NextSibling;
}
}

}


In the above example ... ProcessXmlFile() is a simple and recursive fuction to traverse in between xml node elements,


How to Process Xml Nodes with XmlNode.SelectNodes()?

if you know under which XmlNode your required element is .. then XmlNode.SelectNodes() will work fine ...

Here is a example of How XmlNode.SelectNodes() will work


public void ProcessDynamic()
{
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("test.xml"));
string str = "";
XmlNodeList list;
str = "/carworld/name";
list = doc.SelectNodes(str);
this.ddlcamp.Items.Clear();

ListItem li = new ListItem();

foreach (XmlNode xn in list)
{
if ( xn.Value=="maruthi")
li = new ListItem();
li.Text = cn.Attributes["name"].Value;
li.Value = cn.Attributes["name"].Value;
this.ddlcamp.Items.Add(li);

}
}

}

Happy Coding :)

Wednesday, February 07, 2007

Cookies in ASP.NET

How to Create a Cookie ?

HttpCookie objCookie = new HttpCookie(cookiename);
Response.Cookies.Clear();
Response.Cookies.Add(objCookie);
objCookie.Values.Add(cookiename,cookievalue);
DateTime dtExpiry = DateTime.Now.AddDays(iDaysToExpire);
Response.Cookies[cookiename].Expires =dtExpiry;


How to Read Cookie ?
string value= Request.Cookies[cookiename].Value;

How to Delete a Cookie?
Response.Cookies[cookiename].Expires = DateTime.Now.AddYears(-30);

Checking for Cookie in ASP.NET?

if (Request.Cookies[cookiename] == null)

TextBox2.Text = "No cookie found";

else

TextBox2 .Text = Request.Cookies[cookiename].Value;


How to Avoid HttpExcepiton while Accessing with Session Variable ?

Generally, for user login

if Session["user"] is there then proceed further else redirect to homepage .. for this most commonly we will chek it as

if (Session["user"]!=null )
{
}

This will throw exception , Instead try this


if(Convert.ToBoolean(Session["user"]!=true)
{
Response.Redirect("login.aspx");
}

Friday, February 02, 2007

ASP.NET Frames

How to use iFrames in Asp.net??


1. place your iframe tag where your want in body tag for eg

<iframe id="frame1" style="HEIGHT: 150px" border="0" name="frame1" align="middle" frameBorder="no" width="100%" scrolling="no" runat="server"</iframe>


2. Now, declare one Htmlgeneric control like this

protected System.Web.UI.HtmlControls.HtmlGenericControl frame1;


3. At last ....

HtmlControl frame1 = (HtmlControl)this.FindControl("frame1");
frame1.Attributes["src"] ="target.aspx".ToString ();


write this in your application page load function.........

Javascript ASP.NET

How to use JavaScript in ASP.NET ??

Ans. Its Pretty Simple ............

To use JavaScript in an ASP.NET page, you first need to take two steps:
1.Define the script block that contains the JavaScript
function.
2.Insert the script block programmatically.

for this use either the

Page.RegisterStartupScript()
Page.RegisterClientScriptBlock()


Show MessageBox when page is started !!
To do this, Declare a string variable and assaign the
javascript code as below...

String firstscript = "<script language='javascript'>"+ "alert('Hi! JavaScript world');</script>;";

Now, load this script when ever needed like this ,for ex, write the below code in page_load function

Page.RegisterStartupScript("AlertScript", firstscript);


thats all folks .....

How to Open a Popup window when button clicked?

To popup a window when a button clicked, similar to above

Create one string variable

String popupscript= "<script language='javascript'>"+ "window.open('http://dotnethangout.blogspot.com','DotnetHangout','location=1,status=1,scrollbars=1,
width=100,height=100');</script>;";

now register this script to the page element as same as above

Page.RegisterStartupScript("PopUpWindow", popupscript);


write this in Button click event...



Error: Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.Asp Net SqlConnection

How to avoid the Timeout problem in .net ??????
Ans.
when we deal with huge amount of data, generally it may occur TIMEOUT problem...
in those situations Take care of 3 things ( problem will be almost solved )
1. put the connection timeout property in Connection string
string connstring=" Data Source=localhost;User ID=sa; pwd=secret; Initial catalog=nothwind;connect timeout=900;";
2. set the command timeout for the SqlCommand Object
com.CommandTimeout=0; // this will makes Command to execute unlimited seconds
3. Now .... last but not the least... in the form unload function
destroy the connection object
conn.Dispose();
that's it

Send Mail Asp.NET

How to Send e-mail from asp.net?

MailMessage mail = new MailMessage();
mail.To = "me@something.com";
mail.From = "you@anything.com";
mail.Subject = "this is nothing email.";
mail.Body = "Our text here ";
mail.BodyEncoding = System.Text.Encoding.GetEncoding( "ASCII" );
SmtpMail.SmtpServer = "servername";
SmtpMail.Send( mail );


for further references visit

http://www.systemwebmail.com/faq/3.aspx


How to Change DropdownList selectedItem Dynamically??


1.first clear the selection by dropDown1.ClearSelection() method

2. Now, change your selection accordingly by
dropDown1.Items.FindByText(str).Selected=true;

that's it .... :))