Share Blog

Monday, April 21, 2014

Delegate in C#.net And Asp.net

Delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. It is very similar to the function pointer but with a difference that delegates are a type-safe. We can say that it is the object-oriented implementation of function pointers.

There are three steps for defining and using delegates:

1.               Declaration

A delegate is declared by using the keyword delegate, otherwise it resembles a method declaration.

2.               Instantiation

To create a delegate instance, we need to assign a method (which has same signature as delegate) to delegate.

3.               Invocation

Invoking a delegate is like as invoking a regular method.

Types of delegates

1.               Single cast delegate

A single cast delegate holds the reference of only single method. In previous example, created delegate is a single cast delegate.

2.               Multi cast delegate

A delegate which holds the reference of more than one method is called multi-cast delegate. A multicast delegate only contains the reference of methods which return type is void. The + and += operators are used to combine delegate instances. Multicast delegates are considered equal if they reference the same methods in the same order.

1.               Single cast delegate Example:

Step- New Project ->New Console Application-> Write code


using System;
namespace Delegate_example
{
    //Declaration
    public delegate int mydelegate(int a, int b);//delegates having same signature as method 

    public class del
    {
        public int Sum(int a, int b)
        {
            return a + b;
        }
        public int Sub(int a, int b)
        {
            return a - b;
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            del o = new del();
            // Instantiation : As a single cast delegate
            mydelegate sum = new mydelegate(o.Sum);
            mydelegate sub = new mydelegate(o.Sub);
            //Invocation
            Console.WriteLine("Sum Of The Two Number"+sum(20,10));
            Console.WriteLine("Sub of the two number"+sub(20,10));
           Console.ReadLine();
        }
    }
}

2.    Multi cast delegate Example


using System;

namespace multicast_delegate
{  
    public delegate void MyDelegate(int a,int b);

    class Example
    {
        public void Sum(int a,int b)
        {
            Console.WriteLine("Sum Of The Number   "+(a+b));
        }
        public void Sub(int a, int b)
        {
            Console.WriteLine("Sub Of The Number    " +(a-b));
        }

    }

    class Program
    {
        static void Main(string[] args)
        {
            Example ob = new Example();
            MyDelegate multicast = new MyDelegate(ob.Sum);
            multicast += new MyDelegate(ob.Sub);
            multicast(50,10);
        }
    }
}

2.    Multi cast delegate Another Example Using Asp.net

using System;

public partial class _Default : System.Web.UI.Page
{
    public delegate void mydele(int a,int b);
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        mydele ob = Sum;
        ob += Sub;
        ob += Mul;
        ob += Div;
        ob.Invoke(int.Parse(TextBox1.Text),int.Parse(TextBox2.Text));
        

    }
    public void Sum(int a,int b)
    {
        Label1.Text = (a + b).ToString();
    }
    public void Sub(int a, int b)
    {
        Label2.Text = (a - b).ToString();
    }
    public void Mul(int a, int b)
    {
        Label3.Text = (a *b).ToString();
    }
    public void Div(int a, int b)
    {
        Label4.Text = (a /b).ToString();
    }
}


////////RESULT










Exception Handling in C#.NET

Exceptions are unforeseen errors that happen within the logic of an application.Handling of error occurring at Run-time is known as Exception handling. Exception handling is a way to prevent application from crashing.                      Exception handling using - try-catch 


1.try - Wrap the code in a try block that could possibly cause an exception. If a statement in the try block causes an exception, the control will be immediately transferred to the catch block. We can have more than one catch block for one try block.
                    try
                {
              // Statements that can cause exception.
                       }



2.catch - catches the exception and tries to correct the error and/or handles the exception.
     catch(ExceptionType e)
         {
         // Statements to handle exception.
             }



3.finally - Used to free resources. Finally block contains all cleanup codes. Finally block is guaranteed to execute irrespective of whether an exception has occurred or not.
            finally
              {
         // Statement to clean up.
                         }



4.throw - This keyword is used to throw an exception explicitly.
           catch (Exception e)
             {
            throw (e);
                   }


Step- New Project ->New Console Application-> Write code
using System;


namespace ConsoleApplication1
{
    class Div
    {
        int c;
        public void Division(int a, int b)
        {
            try
            {
                c = a / b;
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine("Exection caught {0}", e);
            }
            finally
            {
                Console.WriteLine("Exection Result {0}", c);
            }
        }
        static void Main(string[] args)
        {
            Div ob = new Div();
            ob.Division(10,0);
            Console.ReadKey();
        }
    }
}
RESULT



Saturday, April 19, 2014

Visual Studio Keyboard Shortcuts

To format document in visual studio
Ctrl + K, D

To comment selected code 
Ctrl + K, C

To uncomment selected code 
Ctrl + K, U

Show intellisense
Ctrl + Space

Covert selected text to UPPERCASE
Ctrl + Shift + U

Covert selected text to LOWERCASE
Ctrl + U

Toggle Full Screen
Alt + Shift + Enter

Build Project
Shift + F6

Build Solution
Ctrl + Shift + B OR F6

Attach the debugger to a process
Ctrl + Alt + P

Expand or Collapse current element
Ctrl + M, M

Collapse all
Ctrl + M, O

Toggle all Outlining
Ctrl + M, L 

Tuesday, April 08, 2014

ASP.NET State Management

State management techniques are used to maintain user state throughout the application. The following are the commonly used state management techniques. The following are the commonly used state management techniques.
View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state
  • Profile Properties

Server Based State Management

Application state, session state, and profile properties all store data in memory on the server.
Session State:  HTTP is a stateless protocol, it can't hold client information on a page. If the user inserts some information and move to the next page, that data will be lost and the user would not be able to retrieve that information. Session provides a facility to store information on server memory. It can support any type of object to store along with our own custom objects. For every client, session data is stored separately, which means session data is stored on a per client basis.

Advantages of Session:-

  1. It helps maintain user state and data all over the application.
  2. It is easy to implement and we can store any kind of object.
  3. Stores client data separately.
  4. Session is secure and transparent from the user.

Session Mode

The following session modes are available in ASP.NET.
  1. Off
  2. InProc
  3. StateServer
  4. SQLServer
  5. Custom

1     1.Off - Disables session state for the entire application.

2.InProc session : When the session state mode is set to InProc, the session state variables are stored on the web server memory inside the asp.net worker process. This is the default session state mode.


     Advantages of InProc session state mode:
    1. Very easy to implement. All that is required is, to set, the session state mode=InProc in      web.config file.
    2. Will perform best because the session state memory is kept on the webserver, within the           ASP.NET worker process(w3wp.exe).
     3. Suitable for web applications hosted on a single server.

Dis-advantages of InProc session state mode:
1. Session state data is lost, when the worker process or application pool is recycled.
2. Not suitable for web farms and web gardens.
Note: 
Web Garden - Web application deployed on a server with multiple processors
Web Farm - Web application deployed on multiple server  .
---------------DEFAULT.ASPX---------------


-------------------DEFAULT2.ASPX CODE-----------


------------------WEB.CONFIG CODE--------
   

3. StateServer :When the session state mode is set to StateServer, the session state variables are stored in a process, called as asp.net state service. This process is different from the          asp.net worker process. The asp.net state service can be present on a web server  

   Steps to follow, to configure asp.net web application to use StateServer:


            1. Start the ASP.NET state Service. To start the asp.net state service
          a) Click Start > Type Run > Press Enter
         b) In the run window, type services.msc and click OK.
         c) In the services window, right click on ASP.NET State Service and select Start.
         2. In web.config set sessionState mode="StateServer"
        3. Set stateConnectionString="tcpip=StateServer:42424"
 Example:<sessionState mode="StateServer"                         stateConnectionString="tcpip=localhost:42424"  
              timeout="20"></sessionState> 
             Advantages of using StateServer session state mode:

1. ASP.NET worker process independent. Survives worker process restart.
2. Can be used with web farms and web gardens.

Dis-advantages of using StateServer session state mode:
1. StateServer is slower than InProc
2. Complex objects, need to be serialized and deserialized

4.SQL SERVER:When the session state mode is set to SQLServer, the session state variables are stored in a SQLServer database.

Steps to follow, to configure asp.net web application to use SQLServer:

 1. Create the ASPState database using aspnet_regsql.exe tool. There are several versions of t      This tool. I am running .NET version 4.0, on a 64 bit operating system. So I will use the version that         is present inC:\Windows\Microsoft.NET\Framework64\v4.0.30319.


     a) click Start > Type Run > Press Enter
       b) Type cmd > Press Enter
       c) In the command prompt type - cd C:\Windows\Microsoft.NET\Framework64\v4.0.30319
       d) Press Enter
       e) Type - aspnet_regsql.exe -S SQLServerName -E -ssadd -sstype p
       f) Press Enter. At this point you should have ASPState Database added.
       g) For help running this tool, please refer to the following MSDN article
       
 2. Set the Session state mode=SQLServer and sqlConnectionString
    If you want to use windows authentication
      <sessionState mode="SQLServer" 
      sqlConnectionString="data source=SQLServerName; integrated security=SSPI"
      timeout="20"></sessionState>
  
    If you want to use sql serevr authentication
     <sessionState mode="SQLServer" 
     sqlConnectionString="data source=SQLServerName; user id=sa; password=pass"

     timeout="20"></sessionState> 
   Note: If you use integrated security(windows authentication), you might get an error stating 

     To resolve this error
     a) click Start > Type Run > Press Enter
     b) Type inetmgr > Press Enter
     c) Expand IIIS and Click on Application Pools.
     d) Right click on ASP.NET v4.0 and select Advanced settings
     e) Change Process Model > Identity to LocalSystem and Click OK

    Advantages of using SQLServer session state mode:
 1. SQLServer is the most reliable option. Survives worker process recycling and SQL Server        restarts.
   2. Can be used with web farms and web gardens.
    3. More scalable than State server and InProc session state modes.

   Dis-advantages of using StateServer session state mode:
    1. Slower than StateServer and InProc session state modes
    2. Complex objects, need to be serialized and deserialized

2. Application state: Application state is a server side state management technique. The date stored in application state is common for all users of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level state management. Data stored in the application should be of small size.  The data in application state is stored once and read several times. Application state uses the HttpApplicationstate class to store and share the data throughout the application.
Events in Global.asax File
Some of the Events in Global.asax file are depicted as follows; this is not a complete list of events.
 Application_Start: This event fires executes when the application starts running
 Application_End: This event ocurs on application shutdown
 Application_Error: This event ocurs when unhandled error occurs
 Session_Start: This event ocurs when new session is started.
 Session_End: This event occurs when session ends.
------------------------------------------------------------------------------------
----------------------------aspx code------------------


using System;

using System.Collections.Generic;
using System.Linq;
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)
    {
      
        Application.Lock();
        TextBox1.Text = Application["t"].ToString();
        TextBox2.Text = Application["o"].ToString();
        Application.UnLock();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Session.Abandon();
    }

}
-----------------------------CODE BEHIND-------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!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>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <table class="style1">
            <tr>
                <td>
                    <asp:Label ID="Label1" runat="server" Text="Total  Visitor"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label2" runat="server" Text="Total Online"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Logout" />
                </td>
                <td>
                    &nbsp;</td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
            </tr>
        </table>
    
    </div>
    </form>
</body>

</html>


------------GLOBAL asax---------------------------
<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        Application.Lock();
        Application["t"]=0;
        Application["o"] = 0;
        Application.UnLock();
        
        // Code that runs on application startup

    }
    
    void Application_End(object sender, EventArgs e) 
    {
        //  Code that runs on application shutdown

    }
        
    void Application_Error(object sender, EventArgs e) 
    { 
        // Code that runs when an unhandled error occurs

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // Code that runs when a new session is started

        //int t, o;
        Application.Lock();
        Application["t"] = int.Parse(Application["t"].ToString()) + 1;
        Application["o"] = int.Parse(Application["o"].ToString()) + 1;
        
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e) 
    {
        // Code that runs when a session ends. 
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer 
        // or SQLServer, the event is not raised.
        //int o;
        Application.Lock();
       Application["o"]= int.Parse(Application["o"].ToString()) -1;
  
        Application.UnLock();

    }
       
</script>




 2.Client Site state: View state, control state, hidden fields, cookies, and query strings all stores the data on the client in various ways.



1.View State:- View state stores page-specific information,when a page post back to the server.When a page is processed,the current state of the page and its controls is hashed into  a string and saved a s a hidden field,such a state of the page is called view state.In any asp.net application view state is maintained by default.
  To disabled the view state on the web page directive:-                                                                       <@page Enableviewstate="false"%>  

  To disable the view state at the coding time:-      
          Enableviewstate=false;                                                                                                    
               OR 
             Page.Eableviewstate=false; 
-----------Code behind-----------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>


<!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>
    
    &nbsp;<asp:Label ID="Label1" runat="server" Text="Name"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
&nbsp;<asp:Label ID="Label2" runat="server" Text="email"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    
    </div>
    </form>
</body>

</html>
-------------axpx.cs code------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
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)
    {
        //Get values from View-State
        if (ViewState["Name"] != null)
        {
            TextBox1.Text = ViewState["Name"].ToString();
        }
        if(ViewState["email"]!=null)
        {
        TextBox2.Text = ViewState["email"].ToString();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        //Set values in View_State
        ViewState["name"] = TextBox1.Text;
        ViewState["email"] = TextBox2.Text;

        //Response.Redirect("defult2.aspx");
    }
}
2.Hidden Fields:ASP.NET allows you to store information in a Hidden-Field control, which renders as a standard HTML hidden field. A hidden field does not render visibly in the browser, but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in the HTTP form collection along with the values of other controls.
3. Cookies: Cookie is a small text file sent by web server and saved by web browser on client machine. Cookies are created when a user's browser loads a particular website. The website sends information to the browser which then creates a text file. Every time the user goes back to the same website, the browser retrieves and sends this file to the website's server.
-The size of cookies 4kb.
-There are two types of cookies available in .Net
  1. Non Persistent / Session Cookies
  2. Persistent Cookies
1.Non Persistent / Session Cookies
Non Persistent cookies are stored in memory of the client browser session, when browsed is closed the non persistent cookies are lost.
2.Persistent Cookies
Persistent Cookies have an expiration date and theses cookies are stored in Client hard drive.


--------------------------------------Code Behind-------------------------------------

    <body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Username"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Password"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Cookies" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>


-------------------------------Default.aspx.cs Code--------------------------------------

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        HttpCookie ob = new HttpCookie("UserInfo");


        ob["UserName"] = TextBox1.Text;

        ob["Password"] = TextBox2.Text;
        ob.Expires = DateTime.Now.AddMinutes(30);


        Response.Cookies.Add(ob);



        Response.Redirect("default2.aspx");

             TextBox1.Text = "";
            TextBox2.Text = "";

    }
-------Second Method------------
  protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Cookies["username"].Value = TextBox1.Text;
        Response.Cookies["Password"].Value = TextBox2.Text;
        Response.Cookies["username"].Expires = DateTime.Now.AddDays(-1);
        Response.Redirect("default2.aspx");
        

    }


---------------------------Code Behind----------------------------------

<body>
    <form id="form1" runat="server">
    <div>
    UserName      <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        <br />
        Password
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </div>
    </form>

</body>


---------------------------Default2.aspx.cs------------------------------

 protected void Page_Load(object sender, EventArgs e)
    {
       


        HttpCookie ob = Request.Cookies["UserInfo"];

        if (ob != null)
        {
            Label1.Text = ob["Username"];
            Label2.Text = ob["Password"];
        }
        else
        {
            Response.Write("Cookies has been Expired");
            return;
        }

    }


-----Second Method---------

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)


            if (Request.Cookies["username"] != null && Request.Cookies["password"] != null)

            {
                Label1.Text = Request.Cookies["username"].Value;


                Label2.Text = Request.Cookies["password"].Value;

            }

    }
    
4.  Query Strings: . A query string is information that is appended to the end of a page URL. They can be used to store/pass information from one page to another to even the same page.
-----------------------------CODE BEHIND------------------


<<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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>
    First Name         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <br />
    last Name        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
    <br />
        <asp:Button ID="Button1" runat="server" Text="Send Data" 
            onclick="Button1_Click" />
    </div>
    </form>
</body>
</html>
-------------------------------BUTTON CODE------------------------
 protected void Button1_Click(object sender, EventArgs e)
    {
Response.Redirect("Default2.aspxfirstname="+Server.UrlEncode(TextBox1.Text)+"&lastname="+Server.UrlEncode(TextBox2.Text));
        //Using String.Replace() function to replace &(ampersand) with %26 
//Response.Redirect("Default2.aspx?firstname="+TextBox1.Text.Replace("&","%26")+ "&lastname="+TextBox2.Text.Replace("&","%26"));
    }
-----------------------Default2.aspx Source Code---------------------
<body>
    <form id="form1" runat="server">
    <div>
     First Name      <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>  
     <br /> <br />  
     Last Name      <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> 
    </div>
    </form>
</body>

-----------------------Default2.aspx  Page Load---------------------

    protected void Page_Load(object sender, EventArgs e)
    {
        // Read the QueryString values 
        Label1.Text = Request.QueryString["firstname"];
        Label2.Text = Request.QueryString["lastname"];
        //Label1.Text = Request.QueryString[0];
        //Label2.Text=Request.QueryString[1];
        //Label1.Text = Request.Params[0];
        //Label2.Text=Request.Params[1];

 }