Tuesday, February 15, 2011

How to check Empty field using JavaScript

function CheckIfEmpty(ctl)
{
/*
Here ctl is the name of
the control, whose value you want to check

*/
if (
      document.getElementById
      ("<%=ctl.ClientID%>").value==""
    )
    {
      alert("Field can not be blank");
      document.getElementById("<%=ctl.ClientID%>").focus();
      return false;
    }
    return true;
} 
<asp:TextBox ID="myTextBox" runat="server"      onblur="javascript:CheckIfEmpty(form1.TextBox1)">
</asp:TextBox>

How to validate all textboxes of the web form on button click event using JavaScript

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default2.aspx.vb" Inherits="Default2" %>

<!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 id="Validation" runat="server">   

<title>Validation</title></head><body>    <!-- title of the page!-->

<form id="form1" runat="server">    <div>

<asp:Label ID="lblMessage" runat="server" Text="Enter the Input:"></asp:Label>

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>   
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>

 </div>   

 <asp:Button ID="Button1" runat="server" Text="Validate" OnClientClick="javascript:validateAllTextBoxes();"/> 
            </form></body></html>



<script type="text/javascript">

    //The following function validates all the textboxes exists in the form
    function validateAllTextBoxes() { 
    //The following valiable lists all the input controls 
        var inputControls = document.getElementsByTagName("input");

        for (i = 0; i < inputControls.length; i++) {

        // The following checkes whether its a textbox or not and its empty or  not

        if (inputControls[i].type == "text" && inputControls[i].value == "") {
            alert("Enter Value in " + inputControls[i].name);
            break;
        } 
       } 
    
     } 
</script>

WaterMark in ASP.Net TextBox using JavaScript

<%@ 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>Untitled Page</title>
    <script type="text/javascript">
    function Watermark()
    {
    var txt=document.getElementById("TextBox1").value;
    if(txt=="Enter User Name")
    {
    document.getElementById("TextBox1").value="";
    }
    
    }
    function RemoveWatermark()
    {
    var txt=document.getElementById("TextBox1").value;
    if(txt=="")
    {
    document.getElementById("TextBox1").value="Enter User Name";
    }
    
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        
        <asp:TextBox ID="TextBox1" Text="Enter User Name" onblur="return RemoveWatermark()" onfocus="return Watermark()" runat="server"></asp:TextBox>
        
    </div>
    </form>
</body>
</html>

Difference between Gridview ,Repeater ,Datalist


* Gridview control binds and displays data in a tabular format and we can edit, update & delete the data.

* Repeater control binds and displays data in a tabular format but we can't edit the data inside repeater control.

* Datalist control binds and display the data in the form of list. 



Supported Funcationalities
Control
Paging
Data Grouping
Provide Flexible Layout
Update,Delete
Insert
Sorting
supported
supported
supported
supported
supported
supported
supported
Not supported
Not Supported
supported
Not Supported
supported
Not supported
supported
supported
Not supported
Not supported
Not supported
Not supported
Not supported
supported
Not supported
Not supported
Not supported

Monday, February 14, 2011

About SQL Commands in ADO.net

A SqlCommand object allows you to specify what type of interaction you want to perform with a database.  For example, you can do select, insert, modify, and delete commands on rows of data in a database table.  The SqlCommand object can be used to support disconnected data management scenarios, but in this lesson we will only use the SqlCommand object alone.  A later lesson on the SqlDataAdapter will explain how to implement an application that uses disconnected data.  This lesson will also show you how to retrieve a single value from a database, such as the number of records in a table.

Creating a SqlCommand Object

Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows:
    SqlCommand cmd = new SqlCommand("select CategoryName from Categories", conn);
The line above is typical for instantiating a SqlCommand object.  It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object.  SqlCommand has a few overloads, which you will see in the examples of this tutorial.

Querying Data

When using a SQL select command, you retrieve a data set for viewing.  To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object.  We'll discuss the SqlDataReader in a future lesson.  The example below shows how to use the SqlCommand object to obtain a SqlDataReader object:
// 1. Instantiate a new command with a query and connection
SqlCommand cmd =
new SqlCommand("select CategoryName from Categories", conn);

// 2. Call Execute reader to get query results
SqlDataReader rdr = cmd.ExecuteReader();

In the example above, we instantiate a SqlCommand object, passing the command string and connection object to the constructor.  Then we obtain a SqlDataReader object by calling the ExecuteReader method of the SqlCommand object, cmd. 
This code is part of the ReadData method of Listing 1 in the Putting it All Together section later in this lesson.

Inserting Data

To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object.  The following code shows how to insert data into a database table:
// prepare command string
 
string insertString = @"
     insert into Categories
     (CategoryName, Description)
     values ('Miscellaneous', 'Whatever doesn''t fit elsewhere')";

 
// 1. Instantiate a new command with a query and connection
 
SqlCommand cmd = new SqlCommand(insertString, conn);

 
// 2. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();

The SqlCommand instantiation is just a little different from what you've seen before, but it is basically the same.  Instead of a literal string as the first parameter of the SqlCommand constructor, we are using a variable, insertString.  The insertString variable is declared just above the SqlCommand declaration. 
Notice the two apostrophes ('') in the insertString text for the word "doesn''t".  This is how you escape the apostrophe to get the string to populate column properly. 
Another observation to make about the insert command is that we explicitly specified the columns CategoryName and Description.  The Categories table has a primary key field named CategoryID.  We left this out of the list because SQL Server will add this field itself.  trying to add a value to a primary key field, such as CategoryID, will generate an exception.
To execute this command, we simply call the ExecuteNonQuery method on the SqlCommand instance, cmd.
This code is part of the Insertdata method of Listing 1 in the Putting it All Together section later in this lesson.

Updating Data

The ExecuteNonQuery method is also used for updating data.  The following code shows how to update data:
// prepare command string
 
string updateString = @"
     update Categories
     set CategoryName = 'Other'
     where CategoryName = 'Miscellaneous'";
 
 // 1. Instantiate a new command with command text only
 
SqlCommand cmd = new SqlCommand(updateString);
 
 // 2. Set the Connection property
 
cmd.Connection = conn;
 
 // 3. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();

Again, we put the SQL command into a string variable, but this time we used a different SqlCommand constructor that takes only the command.  In step 2, we assign the SqlConnection object, conn, to the Connection property of the SqlCommand object, cmd. 
This could have been done with the same constructor used for the insert command, with two parameters.  It demonstrates that you can change the connection object assigned to a command at any time.
The ExecuteNonQuery method performs the update command.
This code is part of the UpdateData method of Listing 1 in the Putting it All Together section later in this lesson.

Deleting Data

You can also delete data using the ExecuteNonQuery method.  The following example shows how to delete a record from a database with the ExecuteNonQuery method:
// prepare command string
 
string deleteString = @"
     delete from Categories
     where CategoryName = 'Other'";
 
 // 1. Instantiate a new command
 
SqlCommand cmd = new SqlCommand();
 
 // 2. Set the CommandText property
 
cmd.CommandText = deleteString;
 
 // 3. Set the Connection property
 
cmd.Connection = conn;
 
 // 4. Call ExecuteNonQuery to send command
 
cmd.ExecuteNonQuery();

This example uses the SqlCommand constructor with no parameters.  Instead, it explicity sets the CommandText and Connection properties of the SqlCommand object, cmd. 
We could have also used either of the two previous SqlCommand constructor overloads, used for the insert or update command, with the same result.  This demonstrates that you can change both the command text and the connection object at any time. 
The ExecuteNonQuery method call sends the command to the database.
This code is part of the DeleteData method of Listing 1 in the Putting it All Together section later in this lesson.

Getting Single values

Sometimes all you need from a database is a single value, which could be a count, sum, average, or other aggregated value from a data set.  Performing an ExecuteReader and calculating the result in your code is not the most efficient way to do this.  The best choice is to let the database perform the work and return just the single value you need.  The following example shows how to do this with the ExecuteScalar method:
// 1. Instantiate a new command
 
SqlCommand cmd = new SqlCommand("select count(*) from Categories", conn);
 
 // 2. Call ExecuteNonQuery to send command
 
int count = (int)cmd.ExecuteScalar();

The query in the SqlCommand constructor obtains the count of all records from the Categories table.  This query will only return a single value.  The ExecuteScalar method in step 2 returns this value.  Since the return type of ExecuteScalar is type object, we use a cast operator to convert the value to int.

To Export the data from Gridview to Excel


protected void Button1_Click(object sender, EventArgs e)
{
string attachment = "attachment; filename=Employee.xls";
        Response.ClearContent();
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/ms-excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        GridView1.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();
}

public override void VerifyRenderingInServerForm(Control control)
    {

    }
If the GridView contains any controls, such as Checkboxes, Dropdownlists, we need to replace the contents with their relevant values. The following recursive function uses Reflection to determine the type of control. The control is deleted in preparation for the Excel export and the relevant value of the control is added.

private void PrepareGridViewForExport(Control gv)
{

    LinkButton lb = new LinkButton();
    Literal l = new Literal();
    string name = String.Empty;
    for (int i = 0; i < gv.Controls.Count; i++)
    {
        if (gv.Controls[i].GetType() == typeof(LinkButton))
        {
            l.Text = (gv.Controls[i] as LinkButton).Text;
  gv.Controls.Remove(gv.Controls[i]);
  gv.Controls.AddAt(i, l);
        }
        else if (gv.Controls[i].GetType() == typeof(DropDownList))
        {
            l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
            gv.Controls.Remove(gv.Controls[i]);
            gv.Controls.AddAt(i, l);
        }
        else if (gv.Controls[i].GetType() == typeof(CheckBox))
        {
            l.Text = (gv.Controls[i] as CheckBox).Checked? "True" : "False";
            gv.Controls.Remove(gv.Controls[i]);
            gv.Controls.AddAt(i, l);
        }
        if (gv.Controls[i].HasControls())
        {
            PrepareGridViewForExport(gv.Controls[i]);
        }
}

without  VerifyRenderingInServerForm method it will give an error
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server


or 

 protected void Button1_Click1(object sender, EventArgs e)
        {
            HtmlForm form = new HtmlForm();

            string attachment = "attachment; filename=Employee.xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/ms-excel";

            StringWriter stw = new StringWriter();

            HtmlTextWriter htextw = new HtmlTextWriter(stw);

            form.Controls.Add(GridView1);

            this.Controls.Add(form);

            form.RenderControl(htextw);

            Response.Write(stw.ToString());

            Response.End();
        }

Dot Net qns

(B) What’ is the sequence in which ASP.NET events are processed?

Following is the sequence in which the events occur:-
• Page_Init.
• Page Load.
• Control events
• Page- Unload event.
Page_init event only occurs when first time the page is started, but Page Load occurs in subsequent request of the page.

(B) In which event are the controls fully loaded?


Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event.5
(B) How can we identify that the Page is Post Back?
Page object has an “IsPostBack” property, which can be checked to know that is the page posted back.

(B) How does ASP.NET maintain state in between subsequent request?


Refer caching chapter.

(A) What is event bubbling?


Server controls like Data grid, Data List, and Repeater can have other child controls inside them. Example Data Grid can have combo box inside data grid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a data grid, data list, repeater), which passed to the page as “ItemCommand” event. As the child control send events to parent it is termed as event bubbling.

(B) How do we assign page specific attributes?

Page attributes are specified using the @Page directive.

(A) How do we ensure view state is not tampered?


Using the @Page directive and setting ‘EnableViewStateMac’ property to True.

(B) What is the use of @ Register directives?


@Register directive informs the compiler of any custom server control added to the page.

(B) What is the use of Smart Navigation property?


It’s a feature provided by ASP. NET to prevent flickering and redrawing when the page is posted back.
Note:- This is only supported for IE browser. Project is who have browser compatibility as requirements have to think some other ways of avoiding flickering.

(B) What is AppSetting Section in “Web.Config” file?


Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-defined values. Example below defined is “Connection String” section, which will be used through out the project for database connection.
<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

(B) Where is View State information stored?


In HTML Hidden Fields.

(I) what is the use of @ Output Cache directive in ASP.NET.


It is used for caching. See more for Caching chapter.

(B) How can we create custom controls in ASP.NET?


User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:.

• Register the ASCX control in page using the <percentage@ Register directive.Example

<%@ Register tag prefix="Accounting" Tag name="footer" Src="Footer.ascx" %>

• Now to use the above accounting footer in page you can use the below directive.

<Accounting: footer runat="server" />

(B) How many types of validation controls are provided by ASP.NET?


There are six main types of validation controls:-

RequiredFieldValidator

It checks whether the control have any value. It is used when you want the control should not be empty.

RangeValidator

It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not be more than eight lengths.

CompareValidator

It checks that the value in controls should match some specific value. Example Textbox TxtPie should be equal to 3.14.

RegularExpressionValidator

When we want the control, value should match with a specific regular expression.

CustomValidator
It is used to define User Defined validation.
Validation Summary
It displays summary of all current validation errors on an ASP.NET page.
Note: - It is rare that some one will ask step by step all the validation controls. Rather they will ask for what type of validation which validator will be used. Example in one of the interviews i was asked how will you display summary of all errors in the validation control...just uttered one word Validation summary.

(B) Can you explain “AutoPostBack”?


If we want the control to automatically post back in case of any event, we will need to check this attribute as true. Example on a Combo Box change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.

(B) How can you enable automatic paging in Data Grid?


Following are the points to be done in order to enable paging in Data grid:-
• Set the “Allow Paging” to true.
• In PageIndexChanged event set the current page index clicked.
Note: - The answers are very short, if you have implemented practically its just a revision. If you are fresher, just make sample code using Datagrid and try to implement this functionality.

(B) What is the use of “GLOBAL.ASAX” file?


It allows to execute ASP.NET application level events and setting application-level variables.

(B) What is the difference between “Web.config” and “Machine.Config”?


“Web.config” files apply settings to each web application, while “Machine.config” file apply settings to all ASP.NET applications.

(B) What is a SESSION and APPLICATION object?


Session object store information between HTTP requests for a particular user, while application object are global across users.

Stack VS Heap in Dot net

Stack vs. Heap: What's the difference?
The Stack is more or less responsible for keeping track of what's executing in our code (or what's been "called").  The Heap is more or less responsible for keeping track of our objects (our data, well... most of it - we'll get to that later.).
Think of the Stack as a series of boxes stacked one on top of the next.  We keep track of what's going on in our application by stacking another box on top every time we call a method (called a Frame).  We can only use what's in the top box on the stack.  When we're done with the top box (the method is done executing) we throw it away and proceed to use the stuff in the previous box on the top of the stack. The Heap is similar except that its purpose is to hold information (not keep track of execution most of the time) so anything in our Heap can be accessed at  any time.  With the Heap, there are no constraints as to what can be accessed like in the stack.  The Heap is like the heap of clean laundry on our bed that we have not taken the time to put away yet - we can grab what we need quickly.  The Stack is like the stack of shoe boxes in the closet where we have to take off the top one to get to the one underneath it.


The Stack is self-maintaining, meaning that it basically takes care of its own memory management.  When the top box is no longer used, it's thrown out.  The Heap, on the other hand, has to worry about Garbage collection (GC) - which deals with how to keep the Heap clean (no one wants dirty laundry laying around... it stinks!).

Sunday, February 13, 2011

DotNet Interview Questions

 
What is a component?
Component is a group of logically related classes and methods. A component is a class that implements the IComponent interface or uses a class that implements IComponent interface.
What is a control?
A control is a component that provides user-interface (UI) capabilities
What is ASP.NET?
Microsoft ASP.NET is a server side technology that enables programmers to build dynamic Web sites, web applications, and XML Web services. It is a part of the .NET based environment and is built on the Common Language Runtime (CLR) . So programmers can write ASP.NET code using any .NET compatible language.
What is the global assembly cache (GAC)?
GAC is a machine-wide cache of assemblies that allows .NET applications to share libraries. GAC solves some of the problems associated with dll’s (DLL Hell).
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.
 
What is instrumentation?
It is the ability to monitor an application so that information about the application’s progress, performance and status can be captured and reported.
What is code review?
The process of  examining the source code generally through a peer, to verify it against best practices.
What is logging?
Logging is the process of persisting information about the status of an application.
What are mock-ups?
Mock-ups are a set of designs in the form of screens, diagrams, snapshots etc., that helps verify the design and acquire feedback about the application’s requirements and use cases, at an early stage of the design process.
What is a Form?
A form is a representation of any window displayed in your application. Form can be used to create standard, borderless, floating, modal windows.
What is a multiple-document interface(MDI)?
A user interface container that enables a user to work with more than one document at a time. E.g. Microsoft Excel.
What is a single-document interface (SDI) ?
A user interface that is created to manage graphical user interfaces and controls into single windows. E.g. Microsoft Word
What is BLOB ?
A BLOB (binary large object) is a large item such as an image or an exe  represented in binary form.
What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish self-updating applications that can be installed and run with minimal user interaction.
What is object role modeling (ORM) ?
It is a logical model for designing and querying database models. There are various ORM tools in the market like CaseTalk, Microsoft Visio for Enterprise Architects, Infagon etc.
What is a private assembly?
A private assembly is local to the installation directory of an application and is used only by that application.
What is a shared assembly?
A shared assembly is kept in the global assembly cache (GAC) and can be used by one or more applications on a machine.
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.
Where do custom controls reside?
In the global assembly cache (GAC).
What is a third-party control ?
A third-party control is one that is not created by the owners of a project. They are usually used to save time and resources and reuse the functionality developed by others (third-party).
What is a binary formatter?
Binary formatter is used to serialize and deserialize an object in binary format.
What is Boxing/Unboxing?
Boxing is used to convert value types to object.
E.g. int x = 1;
object obj = x ;
Unboxing is used to convert the object back to the value type.
E.g. int y = (int)obj;
Boxing/unboxing is quiet an expensive operation.
What is a COM Callable Wrapper (CCW)?
CCW is a wrapper created by the common language runtime(CLR) that enables COM components to access .NET objects.
What is a Runtime Callable Wrapper (RCW)?
RCW is a wrapper created by the common language runtime(CLR) to enable .NET components to call COM components.
What is a digital signature?
A digital signature is an electronic signature used to verify/gurantee the identity of the individual who is sending the message.
What is garbage collection?
Garbage collection is the process of managing the allocation and release of memory in your applications. Read this article for more information.
What is globalization?
Globalization is the process of customizing applications that support multiple cultures and regions.
What is localization?
Localization is the process of customizing applications that support a given culture and regions.
What is MIME?
The definition of MIME or Multipurpose Internet Mail Extensions as stated in MSDN is “MIME is a standard that can be used to include content of various types in a single message. MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to include multiple content, both textual and non-textual. Parts of the message may be images, audio, or text in different character sets. The MIME standard derives from RFCs such as 2821 and 2822”. Quoted from here.

whats the difference between convert.ToInt() and parse.int()


No Difference these are just utility method.

Is String is Value Type or Reference Type in C#?

String is an object (Reference Type).

What are the different types of assemblies available and their purpose?

Private, Public/shared and Satellite Assemblies.
Private Assemblies : Assembly used within an application is known as private assemblies
Public/shared Assemblies : Assembly which can be shared across applicaiton is known as shared assemblies. Strong Name has to be created to create a shared assembly. This can be done using SN.EXE. The same has to be registered using GACUtil.exe (Global Assembly Cache).
Satellite Assemblies : These assemblies contain resource files pertaining to a locale (Culture+Language). These assemblies are used in deploying an Gloabl applicaiton for different languages.


What is the difference between Value Types and Reference Types?

Value Types uses Stack to store the data where as the later uses the Heap to store the data.

What is Boxing and UnBoxing?

Boxing is implicit conversion of ValueTypes to Reference Types (Object) .
UnBoxing is explicit conversion of Reference Types (Object) to its equivalent ValueTypes. It requires type-casting.


What is CTS (Common Type System)?

It defines about how Objects should be declared, defined and used within .NET. CLS is the subset of CTS.

What is CLS (Common Language Specificaiton)?

It provides the set of specification which has to be adhered by any new language writer / Compiler writer for .NET Framework. This ensures Interoperability. For example: Within a ASP.NET application written in C#.NET language, we can refer to any DLL written in any other language supported by .NET Framework. As of now .NET Supports around 32 languages.

What are the different types of Session state management options available with ASP.NET?

ASP.NET provides In-Process and Out-of-Process state management.
In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server.
Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serialization.


What does the "EnableViewState" property do? Why would I want it on or off?

It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.

What is the lifespan for items stored in ViewState?

Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).

What is ViewState?

ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

True or False: To test a Web service you must create a Windows application or Web application to consume this service?

False, the web service comes with a test page and it provides HTTP-GET method to test.

Where on the Internet would you look for Web services?

http://www.uddi.org

What does WSDL stand for?

Web Services Description Language.

True or False: A Web service can only be written in .NET?

False

What is the transport protocol you use to call a Web service?

SOAP (Simple Object Access Protocol) is the preferred protocol.

How many classes can a single .NET DLL contain?

It can contain many classes.

Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator control.

Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

DataTextField property.

Name two properties common in every validation control?

ControlToValidate property and Text property.


Explain the Event Life cycle of ASP.NET 2.0?
The events occur in the following sequence. Its best to turn on tracing(<% @Page Trace=”true”%>) and track the flow of events :
PreInit – This event represents the entry point of the page life cycle. If you need to change the Master page or theme programmatically, then this would be the event to do so. Dynamic controls are created in this event.
Init – Each control in the control collection is initialized.
Init Complete* - Page is initialized and the process is completed.
PreLoad* - This event is called before the loading of the page is completed.
Load – This event is raised for the Page and then all child controls. The controls properties and view state can be accessed at this stage. This event indicates that the controls have been fully loaded.
LoadComplete* - This event signals indicates that the page has been loaded in the memory. It also marks the beginning of the rendering stage.
PreRender – If you need to make any final updates to the contents of the controls or the page, then use this event. It first fires for the page and then for all the controls.
PreRenderComplete* - Is called to explicitly state that the PreRender phase is completed.
SaveStateComplete* - In this event, the current state of the control is completely saved to the ViewState.
Unload – This event is typically used for closing files and database connections. At times, it is also used for logging some wrap-up tasks.
The events marked with * have been introduced in ASP.NET 2.0.

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 does the EnableViewState property signify?
EnableViewState saves the state of an object in a page between postbacks. Objects are saved in a Base64 encoded string. If you do not need to store the page, turn it off as it adds to the page size.
Explain the ASP.NET Page Directives?
Page directives configure the runtime environment that will execute the page. The complete list of directives is as follows:
@ Assembly - Links an assembly to the current page or user control declaratively. 
@ Control - Defines control-specific attributes used by the ASP.NET page parser and compiler and can be included only in .ascx files (user controls).
@ Implements - Indicates that a page or user control implements a specified .NET Framework interface declaratively. 
@ Import - Imports a namespace into a page or user control explicitly.
@ Master - Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files.
@ MasterType - Defines the class or virtual path used to type the Master property of a page.
 @ OutputCache - Controls the output caching policies of a page or user control declaratively.
 @ Page - Defines page-specific attributes used by the ASP.NET page parser and compiler and can be included only in .aspx files.
 @ PreviousPageType - Creates a strongly typed reference to the source page from the target of a cross-page posting.
 @ Reference - Links a page, user control, or COM control to the current page or user control declaratively.
 @ Register - Associates aliases with namespaces and classes, which allow user controls and custom server controls to be rendered when included in a requested page or user control.
What are Master Pages?
Master pages is a template that is used to create web pages with a consistent layout throughout your application. Master Pages contains content placeholders to hold page specific content. When a page is requested, the contents of a Master page are merged with the content page, thereby giving a consistent layout.
How is a Master Page different from an ASP.NET page?
The MasterPage has a @Master top directive and contains ContentPlaceHolder server controls. It is quiet similar to an ASP.NET page.
How do you attach an exisiting page to a Master page?
By using the MasterPageFile attribute in the @Page directive and removing some markup.
How do you set the title of an ASP.NET page that is attached to a Master Page?
By using the Title property of the @Page directive in the content page. Eg:
<@Page MasterPageFile="Sample.master" Title="I hold content" %>
What is a nested master page? How do you create them?
A Nested master page is a master page associated with another master page. To create a nested master page, set the MasterPageFile attribute of the @Master directive to the name of the .master file of the base master page.
What are Themes?
Themes are a collection of CSS files, .skin files, and images. They are text based style definitions and are very similar to CSS, in that they provide a common look and feel throughout the website.
What are skins?
A theme contains one or more skin files. A skin is simply a text file with a .skin extension and contains definition of styles applied to server controls in an ASP.NET page. For eg:
<asp:button runat="server" BackColor="blue" BorderColor="Gray" Font-Bold ="true" ForeColor="white"/>
Defines a skin that will be applied to all buttons throughout to give it a consistent look and feel.
What is the difference between Skins and Css files?
Css is applied to HTML controls whereas skins are applied to server controls.
What is a User Control?
User controls are reusable controls, similar to web pages. They cannot be accessed directly.
Explain briefly the steps in creating a user control?
·         Create a file with .ascx extension and place the @Control directive at top of the page.
·         Included the user control in a Web Forms page using a @Register directive
What is a Custom Control?
Custom controls are compiled components that run on the server and that encapsulate user-interface and other related functionality into reusable packages. They can include all the design-time features of standard ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox.
What are the differences between user and custom controls?
User controls are easier to create in comparison to custom controls, however user controls can be less convenient to use in advanced scenarios.
User controls have limited support for consumers who use a visual design tool whereas custom controls have full visual design tool support for consumers.
A separate copy of the user control is required in each application that uses it whereas only a single copy of the custom control is required, in the global assembly cache, which makes maintenance easier.
A user control cannot be added to the Toolbox in Visual Studio whereas custom controls can be added to the Toolbox in Visual Studio.
User controls are good for static layout whereas custom controls are good for dynamic layout.
Where do you store your connection string information?
The connection string can be stored in configuration files (web.config). 
What is the difference between ‘Web.config’ and ‘Machine.config’?
Web.config files are used to apply configuration settings to a particular web application whereas machine.config file is used to apply configuration settings for all the websites on a web server.
Web.config files are located in the application's root directory or inside a folder situated in a lower hierarchy. The machine.config is located in the Windows directory Microsoft.Net\Framework\Version\CONFIG.
There can be multiple web.config files in an application nested at different hierarchies. However there can be only one machine.config file on a web server.
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.
What method do you use to explicitly kill a users session?
Session.Abandon().
What is a webservice?
Web Services are applications delivered as a service on the Web. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access. Web services are designed to be used by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.
 what is the difference between application state and caching? Application Object and Cached Object both falls under Server side State Management.


Application object resides in InProc i.e. on the same server where we hosted our application.
Cache Object resides on server side/ DownStream/Client Side.


Application Object will be disposed once application will stop.
Cache Object can be disposed using Time based cache dependency.


Only one user can access Application Object at a time hence we have to lock it every time we modify it.


what is boxing and unboxing?Boxing is what happens when a value-type object is assigned to a reference-type variable.
Unboxing is what happens when a reference-type variable is assigned to a value-type variable.

What is the Microsoft.NET?
.NET is a set of technologies designed to transform the internet into a full scale distributed platform. It provides new ways of connecting systems, information and devices through a collection of web services. It also provides a language independent, consistent programming model across all tiers of an application.
The goal of the .NET platform is to simplify web development by providing all of the tools and technologies that one needs to build distributed web applications.
What is the .NET Framework?
The .NET Framework is set of technologies that form an integral part of the .NET Platform. It is Microsoft's managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.
The .NET Framework has two main components: the common language runtime (CLR) and .NET Framework class library. The CLR is the foundation of the .NET framework and provides a common set of services for projects that act as building blocks to build up applications across all tiers. It simplifies development and provides a robust and simplified environment which provides common services to build application. The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality.
What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of code and provides useful services for the implementation of the program. In addition to executing code, CLR provides services such as memory management, thread management, security management, code verification, compilation, and other system services. It enforces rules that in turn provide a robust and secure execution environment for .NET applications.
What is CTS?
Common Type System (CTS) describes the datatypes that can be used by managed code. CTS defines how these types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and high performance code execution. The rules defined in CTS can be used to define your own classes and values.
What is CLS?
Common Language Specification (CLS) defines the rules and standards to which languages must adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit from classes defined in VB.NET or other .NET compatible languages.
What is managed code?
The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. The code that runs within the common language runtime is called managed code.
What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate language (MSIL). The common language runtime includes a JIT compiler for converting this MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this metadata is standardized across all .NET languages, a program written in one language can understand the metadata and execute code, written in a different language. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.
What is JIT?
JIT is a compiler that converts MSIL to native code. The native code consists of hardware specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT converts the MSIL as it is needed during execution. This converted native code is stored so that it is accessible for subsequent calls.
What is portable executable (PE)?PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
What is an application domain?
Application domain is the boundary within which an application runs. A process can contain multiple application domains. Application domains provide an isolated environment to applications that is similar to the isolation provided by processes. An application running inside one application domain cannot directly access the code running inside another application domain. To access the code running in another application domain, an application needs to use a proxy.
How does an AppDomain get created? AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.
What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unit for application development and deployment in the .NET Framework. An assembly contains a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the CLR with the information it needs to be aware of type implementations.
What are the contents of assembly?
A static assembly can consist of four elements:
·         Assembly manifest - Contains the assembly metadata. An assembly manifest contains the information about the identity and version of the assembly. It also contains the information required to resolve references to types and resources.
·         Type metadata - Binary information that describes a program.
·         Microsoft intermediate language (MSIL) code.
·         A set of resources.
What are the different types of assembly?
Assemblies can also be private or shared. A private assembly is installed in the installation directory of an application and is accessible to that application only. On the other hand, a shared assembly is shared by multiple applications. A shared assembly has a strong name and is installed in the GAC.
We also have satellite assemblies that are often used to deploy language-specific resources for an application.
What is a dynamic assembly?
A dynamic assembly is created dynamically at run time when an application requires the types within these assemblies.
What is a strong name?
You need to assign a strong name to an assembly to place it in the GAC and make it globally accessible. A strong name consists of a name that consists of an assembly's identity (text name, version number, and culture information), a public key and a digital signature generated over the assembly.  The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows verification and key pair and signature generation.
What is GAC? What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: sn -k mykey.snk
- in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]
- recompile project, and then install it to GAC in two ways :
·         drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool)
·         gacutil -i abc.dll
What is the caspol.exe tool used for?
The caspol tool grants and modifies permissions to code groups at the user policy, machine policy, and enterprise policy levels.
What is a garbage collector?
A garbage collector performs periodic checks on the managed heap to identify objects that are no longer required by the program and removes them from memory.
What are generations and how are they used by the garbage collector?
Generations are the division of objects on the managed heap used by the garbage collector. This mechanism allows the garbage collector to perform highly optimized garbage collection. The unreachable objects are placed in generation 0, the reachable objects are placed in generation 1, and the objects that survive the collection process are promoted to higher generations.
What is Ilasm.exe used for?
Ilasm.exe is a tool that generates PE files from MSIL code. You can run the resulting executable to determine whether the MSIL code performs as expected.
What is Ildasm.exe used for?
Ildasm.exe is a tool that takes a PE file containing the MSIL code as a parameter and creates a text file that contains managed code.
What is the ResGen.exe tool used for?
ResGen.exe is a tool that is used to convert resource files in the form of .txt or .resx files to common language runtime binary .resources files that can be compiled into satellite assemblies.