Tuesday, 12 February 2013

ASP.NET Page Lifecycle

ASP.NET Page LifeCycle Summary

Here is a summary of the events (and method) which get fired during the processing of the ASP.NET Page Life Cycle as of .NET 4.0.

PreInit
Init
InitComplete
PreLoad
Load
Control events
LoadComplete
PreRender
PreRenderComplete
SaveStateComplete
Render
Unload

PreInit

  • Create dynamic controls
  • Set Master Page dynamically
  • Set Theme dynamically
  • Set/Get Profile properties

Init

  • Control Init fires before Page Init
  • Set/Get Control properties
  • Don't access other controls

InitComplete

  • ViewState tracking switched on
  • Control(s) are accessible but won't have their user data set yet

PreLoad

  • Raised after ViewState has been loaded for Page and Control(s)
  • Raised after processing postback data in Request

Load

  • Load called for Page and then the child Controls recursively
  • Set Control properties and database connections
  • ViewState and POST data available
  • Other Control(s) in Page hierarchy are accessible

Control events eg Button Click

  • Check Page.IsValid where required in code

LoadComplete

  • All controls loaded
  • Postback data and ViewState has been loaded into Page and Control(s)

PreRender

  • PreRender called for Page and then child Control(s) recursively
  • Final changes to Page and Controls before rendering begins

PreRenderComplete

  • Raised after each Control's DataBind is called, which is called when DataSourceID is set
  • Last event before ViewState is saved

SaveStateComplete

  • Raised after ViewState and Control state saved for Page and Control(s)
  • Changes here affect this Page rendering but will not be persisted on a Postback

Render (method not an event)

  • Method not an event
  • Page calls Render on each Control
  • Writes out markup for browser
  • Override in a custom control for custom markup

Unload

  • Cleanup code (such as closing database connections and closing files)
  • Page and Control(s) already rendered so can't be changed

ASP.NET Page LifeCycle Example

Here is a simple example which overrides each of the event handlers for these events and the Render method, as this is not an event. Notice the inclusion of a button onclick event handler which isn't currently utilised. The following shows the HTML output:

OnPreInit
OnInit
OnInitComplete
OnPreLoad
OnLoad
OnLoadComplete
OnPreRender
OnPreRenderComplete
OnSaveStateComplete
Render


using System;
using System.Web.UI;

namespace PageLifeCycle
{
    public partial class _Default : System.Web.UI.Page
    {
        protected override void OnPreInit(EventArgs e)
        {
            Response.Write("OnPreInit <br />");
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            Response.Write("OnInit <br />");
            base.OnInit(e);
        }

        protected override void OnInitComplete(EventArgs e)
        {
            Response.Write("OnInitComplete <br />");
            base.OnInitComplete(e);
        }

        protected override void OnPreLoad(EventArgs e)
        {
            Response.Write("OnPreLoad <br />");
            base.OnPreLoad(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            Response.Write("OnLoad <br />");
            base.OnLoad(e);
        }

        protected void Button_Postback_Click(object sender, EventArgs e)
        {
            Response.Write("Button OnClick on Postback <br />");
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            Response.Write("OnLoadComplete <br />");
            base.OnLoadComplete(e);
        }

        protected override void OnPreRender(EventArgs e)
        {
            Response.Write("OnPreRender <br />");
            base.OnPreRender(e);
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            Response.Write("OnPreRenderComplete <br />");
            base.OnPreRenderComplete(e);
        }

        protected override void OnSaveStateComplete(EventArgs e)
        {
            Response.Write("OnSaveStateComplete <br />");
            base.OnSaveStateComplete(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            Response.Write("Render <br />");
            base.Render(writer);
        }

        protected override void OnUnload(EventArgs e)
        {
            // Response.Write("OnUnload <br />");
            // generates Exception:
            // Response is not available in this context.
            base.OnUnload(e);
        }
    }
}


Print Code in jquery

 
function CallPrint(strid) {
            var prtContent = document.getElementById(strid);
            var WinPrint =
window.open('', '', 'letf=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,sta­tus=0');
            WinPrint.document.write(prtContent.innerHTML);
            WinPrint.document.close();
            WinPrint.focus();
            WinPrint.print();
            WinPrint.close();
            prtContent.innerHTML = strOldOne;
        }


 <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:CallPrint('divPrint');" />

Javascript for calculating age


Javascript for calculating age



<script type="text/javascript">
       function showAge() {
          
           var d = document.getElementById('<%= txtDateOfBirth.ClientID %>').value.split('/');
           var today = new Date();
           var bday = new Date(d[2], d[1], d[0]);
           var by = bday.getFullYear();
           var bm = bday.getMonth() - 1;
           var bd = bday.getDate();
           var age = 0; var dif = bday;
           while (dif <= today) {
               var dif = new Date(by + age, bm, bd);
               age++;
           }
           age += -2;
           document.getElementById("<%=txtCurrentAge.ClientID %>").value = age;
           alert('You are ' + age + ' years old')
       }
</script>

//On page load ..
this.txtDateOfBirth.Attributes.Add("OnBlur", "javascript:return  showAge();");
 

How to clear Cache on logout in c#



Call this method on page load for clearing cache

 public void ClearApplicationCache()
    {
        List<string> keys = new List<string>();

        IDictionaryEnumerator enumerator = Cache.GetEnumerator();

        while (enumerator.MoveNext())
        {
            keys.Add(enumerator.Key.ToString());
        }

        for (int i = 0; i < keys.Count; i++)
        {
            Cache.Remove(keys[i]);
        }
    }

Javascript for character count on keypress



Javascript for character count on keypress 


<script language="javascript" type="text/javascript">
maxL = 1000;
    var bName = navigator.appName;
    function taLimit(taObj) {
        if (taObj.value.length == maxL) return false;
        return true;
    }

    function taCount(taObj, Cnt) {
        objCnt = createObject(Cnt);
        objVal = taObj.value;
        if (objVal.length > maxL) objVal = objVal.substring(0, maxL);
        if (objCnt) {
            if (bName == "Netscape") {
                objCnt.textContent = maxL - objVal.length;
            }
            else { objCnt.innerText = maxL - objVal.length; }
        }
        return true;
    }
    function createObject(objId) {
        if (document.getElementById) return document.getElementById(objId);
        else if (document.layers) return eval("document." + objId);
        else if (document.all) return eval("document.all." + objId);
        else return eval("document." + objId);
    }


 </script>
==================================================
It is used like as mention below


 <asp:TextBox ID="txtImportaintInfo" runat="server" TextMode="MultiLine"
                                    CssClass="textarea_field2"  onpaste="return false" onkeypress="return taLimit(this)" onkeyup="return taCount(this,'myCounter1')"></asp:TextBox>
                                 
<br />     You have <b><span id="myCounter1">1000</span></b>
                                characters remaining for your description...</td>

Friday, 7 December 2012

Get & Set CheckBoxList Selected Item in ASP.net

Use the below Query to Get & Set CheckBoxList Selected Item Using ASP.net

In aspx Page create a CheckBoxList  Example query given below



<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatColumns="3">
<asp:ListItem>Mani</asp:ListItem>
<asp:ListItem>Raja</asp:ListItem>
<asp:ListItem>Durai</asp:ListItem>
</asp:CheckBoxList>

Get CheckboxList Selected Item

strCheckedText = "";
  foreach (ListItem LItem in CheckBoxList1.Items)
   {
    string stBool = LItem.Selected.ToString();
    if (stBool == "True")
      {
       if (strCheckedText == "")
       strCheckedText = LItem.Text;
       else
       strCheckedText = strCheckedText + "|" + LItem.Text;

       }
   }


Clear CheckBoxList Selection

 CheckBoxList1.ClearSelection();

Set CheckboxList Selected Item

string[] ss = strCheckedText.Split('|');
 int iq = 0;
 foreach (ListItem LItem in CheckBoxList1.Items)
 {
  for (int i = 0; i < 3; i++)
   {
    if (ss.Length != iq)
     {
      if (LItem.Text == ss[iq])
        {
          LItem.Selected = true;
          iq++;
         }
       }
      }    
    }

 

Create ThumbnailImage Using ASP.net


This article will help you to learn make thumbnail image through the system.  To upload images to the server, we need a File Upload control and a button control. Asp.Net simplifies the process of uploading images to the server with the FileUpload control. To start with, place a FileUpload control and a button control on your webpage like as follows:




<div>
<asp:Label ID="labelMessage" runat="server" Text="Browse Image:" ForeColor="navy"Width="220"></asp:Label>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Upload" runat="server" Text="Upload" OnClick="Upload_Click" />
<asp:Button ID="Button1" runat="server" Text="button" onclick="Button1_Click" />
</div>

<div>
<asp:Label ID="label1" runat="server" Text="Normal Image (Full size): " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="NormalImage" runat="server" />
</div>

<div>
<asp:Label ID="label2" runat="server" Text="Thumbnail Small Image (50x50)px: " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="ThumbnailImageS" runat="server" />
</div>

<div>
<asp:Label ID="label3" runat="server" Text="Thumbnail Large Image (100x100)px: " ForeColor="navy" Width="220"></asp:Label>
<asp:Image ID="ThumbnailImageM" runat="server" />
</div>


In this article I am using the GetThumbnailImage method of the Image class. This method returns the thumbnail image for the given original image. The syntax for this method is-

public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData);

Coading




protected void Upload_Click(object sender, EventArgs e)
    {
FileUpload1.SaveAs(MapPath("~/ImageRaja/" + FileUpload1.FileName));
System.Drawing.Image img1 = System.Drawing.Image.FromFile(MapPath("~/imgRaja/") + FileUpload1.FileName);

System.Drawing.Image bmp1 = img1.GetThumbnailImage(50, 50, null, IntPtr.Zero);
bmp1.Save(MapPath("~/thumbnailRaja/S/") + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(MapPath("~/thumbnailRaja/L/") + FileUpload1.FileName);
NormalImage.ImageUrl = "~/ ImageRaja /" + FileUpload1.FileName;
ThumbnailImageS.ImageUrl = "~/ thumbnailRaja /S/" + FileUpload1.FileName;
ThumbnailImageM.ImageUrl = "~/ thumbnailRaja /L/" + FileUpload1.FileName;
      }