Sunday, June 30, 2013

What is static variable ?

a.cs
class zzz
{
static void Main()
{
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
public int i = 10;
}

Compiler Error
a.cs(5,26): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.i'

Why did we get an error? Think for thinking is the hardest work there is, which is probably the reason why so few engage in it. If you still haven't got it, let us enlighten you. The same rules for static apply to functions as well as variables. Hence we get the above error.

a.cs
class zzz
{
static void Main()
{
yyy a = new yyy();
yyy b = new yyy();
a.j = 11;
System.Console.WriteLine(a.j);
System.Console.WriteLine(b.j);
yyy.i = 30;
System.Console.WriteLine(yyy.i);
}
}
class yyy
{
public static int i = 10;
public int j = 10;
}

Output
11
10
30


A static variable belongs to the class. Hence if we create a static variable i, no matter how many objects we create that look like yyy, there will be one and only one value of i as there is only one variable i created in memory. Thus we access a static variable by prefacing with the name of the class and not name of object. If the variable is non-static like j then we have to use the syntax as explained earlier i.e. name of object dot name of variable. Thus each time we create an object that looks like yyy we are creating a new/another copy of the variable j in memory. We now have two j's in memory one for a and another for b. Thus j is called an instance variable unlike i. When we change the variable j of a to 11, the j of b remain at 10.

Thus functions are created in memory only once, irrespective of the word static. If a class has no instance or non static variables then it makes no sense to create multiple instances of the object as there will be no way of distinguishing between the copies created.

What is Static function or method ?


a.cs
class zzz
{
static void Main()
{
yyy a;
a=new yyy();
a.abc();
yyy.pqr();
}
}
class yyy
{
public void abc()
{
System.Console.WriteLine("abc");
}
public static void pqr()
{
System.Console.WriteLine("pqr");
}
}

Output
abc
pqr

In this program we have two functions abc and pqr. It is of significance to note that the function pqr has the word static whereas abc does not. If you want to access the static function pqr you say yyy.pqr() and to access the non static function abc you say a.abc(); You can't do the reverse i.e. you cant say a.pqr() and yyy.abc().

a.cs
class zzz
{
static void Main()
{
yyy a;
a=new yyy();
yyy.abc();
a.pqr();
}
}
class yyy
{
public void abc()
{
System.Console.WriteLine("abc");
}
public static void pqr()
{
System.Console.WriteLine("pqr");
}
}

Compiler Error
a.cs(7,1): error CS0120: An object reference is required for the nonstatic field, method, or property 'yyy.abc()'
a.cs(8,1): error CS0176: Static member 'yyy.pqr()' cannot be accessed with an instance reference; qualify it with a type name instead

The word 'static' implies 'free'. Static signifies that you can access a member or a function without creating an object.

Observe that the function Main in zzz is static. This is because we are not creating any object that looks like zzz. The crux is that if you don't want to use 'new' and yet use the function then you must make the function static.

In both cases a dot is used to reference the function. The only difference is that a static member belongs to the class and as such we don't need to create an object to access it. On the other hand, a non-static member, that is the default, can be accessed only via an object of the class. Thus WriteLine is a static function in Console as we did not create an object that looks like Console to access it.

Monday, June 24, 2013

What is the difference between Server.Transfer and Response.Redirect?

Response.Redirect involves a roundtrip to the server whereas Server.Transfer conserves server resources by avoiding the roundtrip. It just changes the focus of the webserver to a different page and transfers the page processing to a different page.
Response.Redirect can be used for both .aspx and html pages whereas Server.Transfer can be used only for .aspx pages.
Response.Redirect can be used to redirect a user to an external websites. Server.Transfer can be used only on sites running on the same server. You cannot use Server.Transfer to redirect the user to a page running on a different server.
Response.Redirect changes the url in the browser. So they can be bookmarked. Whereas Server.Transfer retains the original url in the browser. It just replaces the contents of the previous page with the new one.

Explain the ViewState in ASP.NET?

Http is a stateless protocol. Hence the state of controls is not saved between postbacks. Viewstate is the means of storing the state of server side controls between postbacks. The information is stored in HTML hidden fields. In other words, it is a snapshot of the contents of a page.
You can disable viewstate by a control by setting the EnableViewState property to false.

What is the difference between user and custom controls?

User controls are easier to create whereas custom controls require extra effort.
User controls are used when the layout is static whereas custom controls are used in dynamic layouts.
A user control cannot be added to the toolbox whereas a custom control can be.
A separate copy of a user control is required in every application that uses it whereas since custom controls are stored in the GAC, only a single copy can be used by all applications.

What is a stack? What is a heap? Give the differences between the two?

Stack is a place in the memory where value types are stored. Heap is a place in the memory where the reference types are stored.

How do you prevent a class from being inherited?

In VB.NET you use the NotInheritable modifier to prevent programmers from using the class as a base class. In C#, use the sealed keyword.

Monday, June 17, 2013

what is the purpose of command name and command argument for a control example button? when should we go for this?

This allows you to pass additional parameters to a buttons Command event method identifying the button that called a method. This allows you to have multiple buttons that share similar functionality on your form using the same method when they are clicked rather than implementing a separate click event method for each button.


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Command Button Test</title>
</head>
<body>
   <form id="form1" runat="server">
   <div id="container">
      <h1>Simple Calculator</h1>
      <div class="box">
         <asp:TextBox ID="txtValue1" runat="server" />
         <asp:Button Text="+" runat="server" ID="btnAdd" Width="30px"
            OnCommand="Button_Command" CommandName="add" />
         <asp:Button Text="-" runat="server" ID="btnSubtract" Width="30px"
            OnCommand="Button_Command" CommandName="subtract" />
         <br/>
         <asp:TextBox ID="txtValue2" runat="server" />
         <asp:Button Text="*" runat="server" ID="btnMultiply" Width="30px"
            OnCommand="Button_Command" CommandName="multiply" />
         <asp:Button Text="/" runat="server" ID="btnDivide" Width="30px"
            OnCommand="Button_Command" CommandName="divide" />
      </div>
      <asp:Label ID="labMessage" runat="server" />
   </div>
   </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CommandTest : System.Web.UI.Page
{

  protected void Button_Command(Object o, CommandEventArgs e)
  {
      double dVal1 = 0.0;
      double dVal2 = 0.0;

      bool val1okay = Double.TryParse(txtValue1.Text, out dVal1);
      bool val2okay = Double.TryParse(txtValue2.Text, out dVal2);

     if (val1okay && val2okay)
     {
       double result = 0;

       string op = "";
       switch (e.CommandName)
       {
         case "add":
           op = "+";
           result = dVal1 + dVal2;
           break;
         case "subtract":
           op = "-";
           result = dVal1 - dVal2;
           break;
         case "multiply":
           op = "*";
           result = dVal1 * dVal2;
           break;
         case "divide":
           op = "/";
           result = dVal1 / dVal2;
           break;
       }
       labMessage.Text = txtValue1.Text + op + txtValue2.Text + "=" + result;
     }
     else
     {
       labMessage.Text = "Unable to compute a value with these values";
     }
  }
  
}

Wednesday, June 12, 2013

The Page Life Cycle

Besides from the Applications life cycle there is also the Page life cycle for each page in a website. The following is a list of the page life cycle.
  1. The user makes a request to for a page.
  2. On the webserver, the ASP.NET compile the page (if necessary), or pull from cache (if available).
  3. (Start) Set request and response objects. Determine IsPostBack.
  4. (Init) Initialize page controls (but not their properties). Apply page theme.
  5. (Load) If PostBack, load control properties from view state.
  6. (Validation) Validate page and validator controls
  7. Call control event handlers (for PostBack request).
  8. (Rendering) Save view state. Render controls and display the page.
  9. (Unload) Unload request and response objects. Perform cleanup. Page is ready to be discarded. Return response to user.

What is Bubbled Events ?

Popped up events generated at the time of selecting a row, editing a row, sorting a column, hyperlinking a column, Paging of data in server controls like Repeater, DataList, DataGrid, GridView, DetailsView, FormView and ListView.

What is the significance of AutoEventWireUp attribute?

Gets or sets a value indicating whether events for ASP.NET pages are automatically connected to event-handling functions. 
The AutoEventWireup attribute may have a value of true or false. When an ASP.NET Web Application is created by using Microsoft Visual Studio .NET, the value of the AutoEventWireup attribute is set as false.
We can specify the default value of the AutoEventWireup attribute in the following locations:
• The Machine.config file.
• The Web.config file.
• Individual Web Forms (.aspx files).
• Web User Controls (.ascx files) 

Different ways for sending data across pages in ASP?

* Session

* public properties

What is State management in ASP.NET?

State management is the process by which you maintain state and page information over multiple requests for the same or different pages.
There are 2 types State Management:

1. Client – Side State Management
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator(url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management

a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.