Wednesday, July 29, 2009

ASP.NET - Refresh Part of a Page

We often come across a scenario where we need to update part of a page. We can use IFrame to refresh part of a page.
We can achieve this using Ajax also but here I am discussing how we can achieve without using Ajax.

1. Add a page in the project with name “MyPage.aspx”, copy and paste below code in the aspx page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyPage.aspx.cs" Inherits="MyPage" %>
<!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>Refresh part of page</title>
    <meta http-equiv="Refresh" content="5" />  
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>
</html>



The below line of code in the head section of the above code will refresh the page after every 5 second.



<meta http-equiv="Refresh" content="5" />   



I have placed a Label on the page which will show the time on the page on each refresh of the page.

Put below bold and italic lines of code in the Page_Load method of MyPage.aspx page, this line will refresh the time on each refresh of the page.



protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = "This Page has been refrested at " + DateTime.Now.ToString();
    }



2. Now add another page in the project with name “Refresh.aspx”, copy and paste below code in aspx page of Refresh.aspx.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Refresh.aspx.cs" Inherits="Refresh" %>
<!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>Untitled Page</title>
</head>
<body onload="refreshiFrame();">
    <form id="form1" runat="server">
    <asp:Label ID="Label1" runat="server" Text="" />
    <div>
            <iframe id = "myFrame" src = "MyPage.aspx" frameborder = "0" style="width: 500px;height: 100px">
            </iframe> 
    </div>
    </form>
</body>
</html>


 



I have added an IFrame to achieve the goal of part refresh of the page. I have added src property and set it to MyPage.aspx. I have created MyPage.aspx in the first page.

I have also put a label outside the iframe, it will show the Date and time when Refresh.aspx page will load.

Copy and paste below bold line of code on Page_Load method



    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = DateTime.Now.ToString();
    }



Now run Refresh.aspx page, you will notice that the time on the Refresh.aspx won’t change but the time on MyPage.aspx will change after every 5 seconds

Happy Coding :)

Monday, July 27, 2009

Analysis of Typed VS UnTyped DataSet

1. Create a project with name Analysis.

2. Follow the steps provided in this link to create typed dataset http://support.microsoft.com/kb/320714

2. Create three buttons with name “Typed”, “Untyped” and “Difference” on the Form.

3. Declare two class level variable

4. Copy and paste below code in “Typed” method.


Private Sub Typed_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
         Dim watch As Stopwatch = New Stopwatch()
         watch = Stopwatch.StartNew()
         Dim cn As SqlConnection = New SqlConnection("ConnectionString")
         Dim cmd As SqlCommand = New SqlCommand("select * from [Alphabetical list of products]", cn)   
         Dim
da As SqlDataAdapter = New SqlDataAdapter(cmd)
         Dim tds As dsProducts = New dsProducts()
         da.Fill(tds, tds.Tables(0).TableName)
         Dim rowCount As Integer = tds.Tables(0).Rows.Count
         Dim i As Integer
         Dim str As String = String.Empty
         Dim intValue As Integer = 0
         Dim sortValue As Double = 0
         Dim bln As Boolean
         For i = 1 To rowCount
                  intValue = tds.Alphabetical_list_of_products(0).ProductID
                  intValue = tds.Alphabetical_list_of_products(0).SupplierID
                  intValue = tds.Alphabetical_list_of_products(0).CategoryID
                  str = tds.Alphabetical_list_of_products(0).CategoryName
                  str = tds.Alphabetical_list_of_products(0).ProductName
                  str = tds.Alphabetical_list_of_products(0).QuantityPerUnit
                  sortValue = tds.Alphabetical_list_of_products(0).UnitPrice
                  intValue = tds.Alphabetical_list_of_products(0).UnitsInStock
                  intValue = tds.Alphabetical_list_of_products(0).UnitsOnOrder
                  intValue = tds.Alphabetical_list_of_products(0).ReorderLevel
                  bln = tds.Alphabetical_list_of_products(0).Discontinued
        
Next
         tds.Dispose()
         watch.Stop()
         TypedDataset = watch.ElapsedTicks
         MessageBox.Show(
"Typed " + Convert.ToString(TypedDataset))
End Sub



5. Copy and paste below code in “UnTyped” method.


Private Sub UnTyped_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
         Dim watch As Stopwatch = New Stopwatch()
         watch = Stopwatch.StartNew()
         Dim cn As SqlConnection = New SqlConnection("ConnectionString")
         Dim cmd As SqlCommand = New SqlCommand("select * from [Alphabetical list of products]", cn)        
         Dim
da As SqlDataAdapter = New SqlDataAdapter(cmd)
        
Dim tds As DataSet = New DataSet()
         da.Fill(tds)
        
Dim rowCount As Integer = tds.Tables(0).Rows.Count
        
Dim i As Integer
        
Dim str As String = String.Empty
        
Dim intValue As Integer = 0
        
Dim sortValue As Double = 0
        
Dim bln As Boolean
        
For i = 0 To rowCount - 1
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"ProductID"))
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"SupplierID"))
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"CategoryID"))
                  str = tds.Tables(0).Rows(i).Item(
"CategoryName").ToString()
                  str = tds.Tables(0).Rows(i).Item(
"ProductName").ToString()
                  str = tds.Tables(0).Rows(i).Item(
"QuantityPerUnit").ToString()
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"UnitPrice"))
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"UnitsInStock"))
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"UnitsOnOrder"))
                  intValue = Convert.ToInt32(tds.Tables(0).Rows(i).Item(
"ReorderLevel"))
                  bln = Convert.ToBoolean(tds.Tables(0).Rows(i).Item(
"Discontinued"))
        
Next
        
tds.Dispose()
         watch.Stop()
         UnTypedDataset = watch.ElapsedTicks
         MessageBox.Show(
"Untyped " + Convert.ToString(UnTypedDataset))
End Sub






6. Copy and paste below code in “Difference” method.

Private Sub Difference_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
         MessageBox.Show(
"Difference " + Convert.ToString(TypedDataset - UnTypedDataset))
End Sub


7. Now, we are all set to run application.

8. Click on type and un-typed.

9. Now click on difference, you will see the difference of execution time between typed and un-typed.

10.When you run the above code first time, you will notice that Typed dataset take 50-70 times more compare to un-typed dataset, it is because typed dataset read the xsd file and keep it in the memory for reference.

Now let’s have a look on the memory consumption and other things, it will give more clear understanding.

Typed DataSet - Summary


Untyped DataSet - Summary


In above two diagrams you can see the difference in Heap Statistics, Garbage Collection and GC Handles Statistics.

Typed DataSet – Allocated Bytes in Heap


Untyped DataSet-Allocated bytes in heap


In above diagram check right top, for typed total byte allocation is 842,423 and for un-typed byte allocation is 522,144.

Typed DataSet – By Age


Untyped DataSet – By Age


In above two diagrams, lifetime of objects in typed dataset is almost 25 sec and the age of un-typed is around 5 sec.

Typed DataSet – Object by address


Untyped DataSet - Objects by address


In above two diagram, typed has gen 0 and gen 1 which means garbage collector will run twice to clean it where as in un-typed it will run only once. Typed has also LOH which is large object heap.


Typed DataSet - Time Line


Untyped DataSet – Time Line


In the above diagram, typed dataset objects survive garbage collection and are prompted to next generation whereas in un-typed it is done in one generation only.

 Points to consider to choose between Typed DataSet and Untyped DataSet


Typed DataSet


·   It provides additional methods, properties and events and thus it makes it easier to use.


·   You will get type mismatch and other errors at compile time.


·   You will get advantage of intelliSense in VS. NET


·   Performance is slower in case of strongly typed dataset.


·   Typed DataSet has a schema


·   In complex environment, strongly typed dataset's are difficult to administer.


Untyped DataSet


·      It is not as easy to use as strongly typed dataset.


·      You will get type mismatch and other errors at runtime.


·      You can't get an advantage of intelliSense.


·      Performance is faster in case of Untyped dataset.


·      An Untyped DataSet does not have schema


·      Untyped datasets are easy to administer.

Sunday, July 26, 2009

Static Class and Static Method and Static Member

I am assuming that you know static class and static members refer http://msdn.microsoft.com/en-us/library/79b3xss3.aspx to know about it.

Let’ examine the static class and static members in detail using below points

1. Static Class and NonStatic Class are same?


Lets Create static class like below:

  public static class StaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }
        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }


MyFirstMethod and MySecondMethod can be called using class name like below.

StaticClass.MyFirstMethod();        
StaticClass.MySecondMethod();


And non static class like below:

public class NonStaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }


        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



MyFirstMethod and MySecondMethod can be called using class name like below.

NonStaticClass.MyFirstMethod();  
NonStaticClass.MySecondMethod();



StaticClass and NonStaticClass have same behavior so far. If the behavior is same why do we need static class, let’s examine it more.

2. Static Class and NonStatic Class are not same because Static class is sealed?



As we know static class is sealed, we can’t inherit static class, let’ create a class MyClass and try to inherit static class like below:

 class MyClass : StaticClass
    {    

    }



You will get compile time error “'StaticClassTest.MyClass': cannot derive from static class 'StaticClassTest.StaticClass'

Now make the NonStaticClass which we have just created as sealed like below:

   public sealed class NonStaticClass
    {
        public static void MyFirstMethod()
        {
            //Code Goes Here
        }

        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



Now inherit NonStaticClass to MyClass


class MyClass : NonStaticClass
    {       


    }



You will get compile time error “'StaticClassTest.MyClass': cannot derive from sealed type 'StaticClassTest.NonStaticClass'”

Still StaticClass and NonStaticClass are same, So far all the features provided by StaticClass can be achieved using NonStaticClass. If the behaviour same what is the difference, let’s examine it more

3. Static Class and NonStatic Class are not same because Static class cannot contain instance constructors?

Let’s modify the StaticClassTest and make it like below which is having constructor

public static class StaticClass
    {
        static StaticClass(string MyName)
        {
        }

        public static void MyFirstMethod()
        {
            //Code Goes Here
        }

        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



You will get compile time error “'StaticClassTest.StaticClass.StaticClass(string)': a static constructor must be parameterless”

Let’s modify the NonStaticClass and make it like below which is having constructor


public sealed class NonStaticClass
    {
        public NonStaticClass(string MyName)
        {
            //Code Goes Here
        }


        public static void MyFirstMethod()
        {
            //Code Goes Here
        }


        public static void MySecondMethod()
        {
            //Code Goes Here
        }
    }



Compile the application, it will compile without any error.

Call MyFirstMethod of NonStaticClass like below

NonStaticClass.MyFirstMethod();



Put a break point on the constructor of NonStaticClass. You will notice constructor won’t be called only MyFirstMethod will called.

Now create object of NonStaticClass like below

NonStaticClass objNonStaticClass = new NonStaticClass("test");


Constructor of NonStaticClass will be called at this time.

Conclusion:

Normal class with all static members is equivalent to static members of static Class, if you don't intend to inherit normal class.
Normal sealed class with all the static members is equivalent to static members of static Class.
Normal sealed class with all static members and a paramerized constructor is not equivalent to static members of static Class because static class doesn’t permit paramerized constructor.

Decision to use static class
Static classes should be used when a class doesn't have any behaviour as such. Like utility or helper class, the methods in utility and helper class need to be called several times, there is no need to create instance of the class on each call. This will improve the performance as object creation is not involved on each call.

Why static class will improve performance?

There is division of memory within a process

1. Stack
2. Heap
3. Static, which is High Frequency Heap.

The member data of static class is stored in High Frequency Heap which is handled differently than regular object heap. This area of heap is not garbage collected. It means GC doesn't have overhead like regular class which need to be garbage collected when it is unreachable. Static class doesn't get constructed until it is used.

Wednesday, July 8, 2009

Create Dynamic DropDownList

1. Create a DynamicDropDownlist.aspx and place a placeholder and two buttons with name btnCreate and btnRetrieve. 



<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
<
asp:Button ID="btnCreate" runat="server" Text="Create DropDownList" />
<
asp:Button ID="Retrieve" runat="server" Text="Button" onclick="btnRetrieve_Click" />


2. Create a class level Control variable and assign null to it.


Control cause = null;

3. Create CreateDropDownListControl method. This method will create dropdownlist, copy and paste below code.



public static Control GetPostBackControl(Page page)
{
      Control control = null;
      
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
      
if (ctrlname != null && ctrlname != string.Empty)
      {
            control = page.FindControl(ctrlname);
      }
      
else
      
{
            
foreach (string ctl in page.Request.Form)
            {
                  Control c = page.FindControl(ctl);
                  
if (c is System.Web.UI.WebControls.Button)
                  {
                        control = c;
                        
break;
                  }
            }
      }
      return control;
}


4. Create Page_Init method, copy and paste below code.


protected void Page_Init(object sender, EventArgs e)
{
      if (IsPostBack)
      {
            //Method to get the control which caused postback
            
cause = GetPostBackControl(Page);
            
//To make sure new dropdownlist get create on click of
create DropDownList
            
if (cause != null && cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
            
//To re-create control in case of any postback excluding click of Create DropDownList
            
else if (cause == null || !cause.ID.Equals("btnCreate"))
            {
                  CreateDropDownListControl();
            }
      }
}

5. OnSelectedIndexChanged method will return value of the selected dropdownlist index,Copy and paste below code. 



protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
      DropDownList ddl = (DropDownList)sender;
      Response.Write(ddl.SelectedItem.Text);
}


6. btnRetrieve_Click method will return value of the all selected dropdownlist index,Copy and paste below code.



protected void btnRetrieve_Click(object sender, EventArgs e)
{
      int ddlCount = Convert.ToInt32(Session["Count"].ToString());
      for (int i = 0; i < ddlCount; i++)
      {
            Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
      }
}


Lets' put all together in DynamicDropDownlist.aspx.cs file.



using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;






public partial class DynamicDropDownlist : System.Web.UI.Page
{
      Connrol cause = null;
      
protected void Page_Init(object sender, EventArgs e)
      {
            
if (IsPostBack)
            {
                  
//Method to get the control which caused postback
                  cause = GetPostBackControl(Page);
                  
//To make sure new dropdownlist get create on click of Create DropDownList
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
                  
//To re-create control in case of any postback excluding click of Create DropDownList
                  
else if (cause == null || !cause.ID.Equals("btnCreate"))
                  {
                        CreateDropDownListControl();
                  }
            }
      }
      public static Control GetPostBackControl(Page page)
      {
            
Control control = null;
            
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
            
if (ctrlname != null && ctrlname != string.Empty)
            {
                  control = page.FindControl(ctrlname);
            }
            
else
            
{
                  
foreach (string ctl in page.Request.Form)
                  {
                        
Control c = page.FindControl(ctl);
                        
if (c is System.Web.UI.WebControls.Button)
                        {
                              control = c;
                              
break;
                        }
                  }
             }
             
return control;
      }

      protected void Page_Load(object sender, EventArgs e)
      {
      }




      protected void btnRetrieve_Click(object sender, EventArgs e)
      {
            
int ddlCount = Convert.ToInt32(Session["Count"].ToString());
            for (int i = 0; i < ddlCount; i++)
            {
                  Response.Write(
"Selected Dropdownlist values are " + Request.Form["ddl" + i.ToString()] + "</br>");
            }
      }


      protected void CreateDropDownListControl()
      {
            
if (Session["Count"] == null)
            {
                  
DropDownList ddl = new DropDownList();
                  ddl.ID =
"ddl0";
                  ddl.AutoPostBack =
true;
                  ddl.Items.Add(
new ListItem("Test0", "0"));
                  ddl.Items.Add(
new ListItem("Test1", "1"));
                  ddl.SelectedIndexChanged +=
new EventHandler
OnSelectedIndexChanged);
                  PlaceHolder1.Controls.Add(ddl);
                  Session[
"Count"] = "1";
            }
            
else
            
{
                  
int ctrlCount = 0;
                  
if (cause != null && cause.ID.Equals("btnCreate"))
                  {
                        
ctrlCount =
Convert.ToInt32(Session["Count"].ToString()) + 1;
                        Session[
"Count"] = (Convert.ToInt32(Session["Count"].ToString()) + 1).ToString();
                  }
                  
else
                  
{
                        ctrlCount =
Convert.ToInt32(Session["Count"].ToString());
                  }
                  
for (int i = 0; i < ctrlCount; i++)
                  {
                        
DropDownList ddl = new DropDownList();
                        ddl.ID =
"ddl" + i.ToString();
                        ddl.AutoPostBack =
true;
                        ddl.Items.Add(
new ListItem("Test" + i.ToString(), "0"));
                        ddl.Items.Add(
new ListItem("Test" + (i + 1).ToString(), "1"));
                        ddl.SelectedIndexChanged +=
new EventHandler(OnSelectedIndexChanged);
                        PlaceHolder1.Controls.Add(ddl);
                  }
            }
      }




      protected void OnSelectedIndexChanged(object sender, EventArgs e)
      {
            DropDownList ddl = (DropDownList)sender;
            Response.Write(ddl.SelectedItem.Text);
      }


}


Happy Coding :)

Site Meter