Wednesday, June 24, 2009


The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class.

What is a sealed class? 

It is a class, which cannot be subclassed. it is a good practice to mark your classes as sealed, if you do not intend them to be subclassed.

The two primary uses of the sealed keyword are as they apply to the class and as they are applied to elements of the class.You might also apply the sealed keyword to virtual functions that you are overriding in a child class.  This has the effect of allowing you to prevent the virtual function from being overridden in the child class past the class where it has been sealed.

// Sealed class
sealed class SealedClass

In the following code, I create a sealed class SealedClass and use it from Class1. If you run this code, it will work fine. But if you try to derive a class from sealed class, you will get an error. 

class Class1
      static void Main(string[] args)
              SealedClass sealedCls =
new SealedClass();
              int total = sealedCls.Add(4, 5);
              Console.WriteLine("Total = " + total.ToString());

// Sealed class
sealed class SealedClass
       public int Add(int x, int y)
           return x + y;

In C# a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overrided method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.  

using System;
class MyClass1 
   public int x; 
   public int y;

   public virtual void Method()
 Console.WriteLine("virtual method");

class MyClass : MyClass1
   public override sealed void Method()
 Console.WriteLine("sealed method");

class MainClass 
   public static void Main() 
      MyClass1 mC = new MyClass(); 
      mC.x = 110;
      mC.y = 150;
      Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y); 


Tuesday, June 23, 2009

Basic ASP.NET Interview Questions - Part 2

1.What attribute do you use to hide a public .NET class from COM?
Use the ComVisible attribute to select which public .NET classes and members are visible to COM. This attribute applies hierarchically for the assembly, class, and member levels.

2.Why can’t you open a new browser window using server-side code? How would you display a page in a new window with a client-side script?
Server-side code can execute tasks only on the server. To perform a task on the client’s computer, such as opening a new browser window, the code needs to run on the client.

3.How do you declare an unmanaged procedure within .NET?
Use the DllImport attribute or a Visual Basic .NET Declare statement to declare an unmanaged procedure for use with a .NET assembly. The DllImport attribute is found in the System.Runtime.InteropServices namespace.

4.Which ASP.NET authentication mode is best suited to identifying and authorizing users who belong to a corporate network?
Windows authentication is best suited to authenticating users of a corporate network because it uses the accounts and permissions that already exist for network users.

5.What is the difference between Windows and Forms authentication user lists in Web.config?
User lists for Windows authentication are included in the
element of Web.config. User lists for Forms authentications are included in the
element of Web.config or as part of an external users database or file.

6.How does the Secure Sockets Layer (SSL) provide security in a Web application?
SSL protects data exchanged between a client and a Web application by encrypting the data before it is sent across the Internet.

7.What permissions do Web applications run under by default?
By default, Web applications run as the ASPNET user, which has limited permissions equivalent to the Users group.

8.Why is the Machine.config file important to deployed Web applications?
The Machine.config file controls many aspects of how Web applications run, including how processes are recycled, what types of request queue limits are imposed, and what interval is used when checking if users are still connected.

9.How do you configure a setup project to install an application over the Web?
To configure a setup project to install an application over the Web, select the Web Bootstrapper option from the setup project’s properties. This setting allows the Windows Installer to be downloaded and installed over the Web.

10.How do you distribute shared components as part of an installation program?
Shared components should be included as a merge module within the setup project. Merge modules manage the installation of shared components so that they’re not unnecessarily overwritten and so that they can be safely removed when no longer used. Unlike regular setup projects, merge modules can’t be installed by themselves—they can be installed only as part of an application installation.

11.How does deploying to a Web farm or a Web garden affect Session state in a Web application?
Web applications that are deployed to a Web farm or a Web garden need to identify a Session state provider in their Web.config file. This is because a single client’s requests can be directed to different processes over the course of his or her session. The Session state provider allows each different process to access the client’s Session state.

12.How do unit, integration, and regression testing relate to each other?
Unit testing is the foundation that ensures that each piece of code works correctly. Integration testing extends this concept by verifying that pieces work together without errors. Regression tests are made up of the existing unit and integration tests, which are run on a regular schedule to assure that new code did not break previously working code.

13.Why is load testing likely to be more important for a Web application than for a stand-alone Windows application?
Because Web applications can be public on the Internet, they can have hundreds, thousands, or even millions of users. Load tests let you simulate the expected demand to locate resource conflicts, performance bottlenecks, and other problems that aren’t apparent in single-user tests.

14.What is the difference between the Debug and Trace classes?
Under the default environment settings, code using the Debug class is stripped out of release builds, while code using the Trace class is left in. The classes are otherwise equivalent.

15.What are the two special steps you need to take to ensure that a COM component can use a component from a .NET assembly?
To use a .NET component from a COM tool, such as VBScript, you must:
•Register the .NET assembly in the system registry using RegAsm.exe.
•Make sure that the COM component can find the .NET assembly, either by placing the .NET assembly in the global assembly cache, by placing the two components in the same folder, or by following the other assembly-probing rules.

16.When do you generally create a web user control?
You generally create a web user control when you want to create a group of controls that can be reused throughout a project to perform some logical unit of work.

17.When do you generally create a custom control ?
You generally create a custom control when you want to combine one or more existing controls into a compiled assembly that can be easily reused in many different projects.

18.How is deriving important to creating custom Web controls?
Both composite and rendered custom controls are derived from the WebControl base class. That class provides the methods that you override to create the appearance of the custom control.

19.What is the most important method to override when you’re creating a composite custom control?
You override the CreateChildControls method to add existing controls to a composite custom control.

20.How is raising a post-back event in a composite control different from raising a post-back event in a rendered control?
In a composite control, you can use one of the contained controls to raise a post-back event. In a rendered control, you must implement the IPostBackEventHandler interface and write a client-side script to raise a post-back event.

21.Write a directive to cache responses for a Web form for 30 seconds, storing different cache responses based on the value of the lstNames control.
<%@ OutputCache Duration=”30” VaryByParam=”lstNames” %>

22.A Web form uses fragment caching to store a frequently used user control. At run time, an Object not found error occurs whenever the page is refreshed. What is a likely cause of the error?
The most likely cause is that the user control is referenced in code after it has been cached. Once cached, a user control’s properties and methods are no longer available.

23.How can you detect when application data is about to be removed from the cache?
Use the onRemoveCallback delegate.

24.What is the advantage of using CSS rather than in-line styles for formatting a Web application?
Using CSS allows you to maintain formatting separately from the content of your Web forms, so changes are easier to make and consistency is easier to maintain.

25.Why would you create a style for a class rather than for an HTML element?
You create style classes when you want to apply the same formatting to different types of elements within an application. For example, you might want to create an emphasis style class that applies the same formatting to any text, control, heading, or image that you want to draw the user’s attention to.

26.How do CSS and XSL relate to each other when it comes to formatting a Web application?
CSS and XSL are complementary techniques for formatting. CSS determines the font, color, size, background, and other appearance aspects of HTML elements on a Web page. XSL is used to transform XML files into HTML output. In this way, XSL controls the position and appearance of items based on their content. Used together, XSL performs the high-level tasks of composition and layout while CSS performs the low-level tasks of applying fonts, colors, and other appearance features

27.What are the differences between HTML and XML?
1. In XML, you create your own element names to identify hierarchical nodes of data.
2.XML syntax is much stricter than HTML: elements must always have end-tags, element names are case sensitive, attribute values must always be enclosed in quotation marks, and nested elements must be terminated within their parent elements.
3.XML identifies data conceptually based on the data’s content, rather than based on the type of formatting to apply.

28.Which HTML attribute does the server control’s ToolTip property map to in the HTML rendered by ASP.NET?
The ToolTip property is rendered as the title attribute at run time.

29.What is the difference between the CurrentCulture property and the Current­UICulture property?
The CurrentCulture property affects how the .NET Framework handles dates, currencies, sorting, and formatting issues. The CurrentUICulture property determines which satellite assembly is used when loading resources.

30.How do you detect the user’s culture?
Use the Request object’s UserLanguages array. The value at element 0 corresponds to one of the culture codes used by the CultureInfo class. For example: SLang = Request.UserLanguages(0)
SLang = Request.UserLanguages(0)

31.What is a neutral culture?
Neutral cultures represent general languages without region-specific differences, such as currency. For example, the “es” culture code represents Spanish.

Basic ASP.NET Interview Questions - Part 1

1.What is the main difference between an ASP.NET Web application and a traditional Windows application.
ASP.NET Web applications runs under common language runtime using managed code where as Unmanaged Windows application runs under Windows using unmanaged code.

2.What are the two main parts of the .NET Framework?
The two main parts of the .NET Framework are
1.The common language runtime (CLR).
2.The .NET Framework class library.

3.When can’t you use ASP.NET to create a Web application?
When you are developing for non–Microsoft Windows Web servers, such as Linux/Apache.

4.List the four major differences between Web and Windows applications.
•Web forms cannot use the standard Windows controls. Instead, they use server controls, HTML controls, user controls, or custom controls created specially for Web forms.
•Web applications are displayed in a browser. Windows applications display their own windows and have more control over how those windows are displayed.
•Web forms are instantiated on the server, sent to the browser, and destroyed immediately. Windows forms are instantiated, exist for as long as needed, and are destroyed.
•Web applications run on a server and are displayed remotely on clients. Windows applications run on the same machine they are displayed on.

5.Describe the life cycle of a Web application: When are Web forms instantiated and how long do they exist?
A Web application starts with the first request for a resource within the application’s boundaries. Web forms are instantiated when they are requested. They are processed by the server and are abandoned immediately after the server sends its response to the client. A Web application ends after all client sessions end.

6.How do you preserve persistent data, such as simple variables, in a Web application?
You can preserve data in state variables, such as ApplicationState, SessionState, or ViewState.

7.How does the .NET Framework organize its classes?
The .NET Framework uses namespaces to organize its classes.

8.In Visual Basic .NET, what is the difference between a class module and a code module?
Class modules are instantiated at run time to create objects that provide separate storage for variables and properties in each instance. Code modules do not have instances, so any module-level variables they use are shared among calls to the module’s procedures.

9.In Visual C#, how do you declare a method to make it available without having to first instantiate an object from the class?
To create a method that can be called without instantiating an object, declare that method as static.

10.How do you call a member of a base class from within a derived class?
To refer to a member of a base class in Visual Basic .NET, use the MyBase keyword. To refer to a member of a base class in Visual C#, use the base keyword.

11.Where would you save the following data items so that they persist between requests to a Web form?
•A control created at run time
•An object that provides services to all users
•User preferences
•Save controls created at run time in the Page object’s ViewState.
•Save objects that provide services to all users in the Application state.
•Save user preferences in SessionState.

12.What is the main difference between the Button server control and the Button HTML control?
When clicked, the Button server control triggers an ASP.NET Click event procedure on the server. The Button HTML control triggers the event procedure indicated in the button’s onclick attribute, which runs on the client.

13.How do you get several RadioButton controls to interoperate on a Web form so that only one of the RadioButton controls can have a value of True/true at any given time?
Set the GroupName property of each RadioButton to the same name.

14.Why does ASP.NET perform validation on both the client and the server?
Client-side validation helps avoid round-trips to the server. Validating on the client ensures that the data is valid before it is submitted, in most cases. However, because validation might be turned off (or maliciously hacked) on the client, data must be revalidated on the server side. This provides full assurance that the data is valid while avoiding as many round-trips as possible.

15.What types of validation would you use to verify that a user entered a valid ­customer number?
You would use a RequiredFieldValidator and a RegularExpressionValidator. If you have access to a list of expected customer numbers, you could replace the RegularExpressionValidator with a CustomValidator that checked the list.

16.Explain the difference between handling transactions at the data set level and at the database level.
Data sets provide implicit transactions, because changes to the data set aren’t made permanent in the database until you call the Update method. To handle transactions in a data set, process the Update method and check for errors. If errors occur during an update, none of the changes from the data set is made in the database. You can try to correct the error and resubmit the update, or you can roll back the changes to the data set using the RejectChanges method.

Databases provide explicit transactions through the Transaction object. You create a Transaction object from a database connection and then assign that Transaction object to the commands you want to include in the transaction through the command object’s Transaction property. As you perform the commands on the database, you check for errors. If errors occur, you can either try to correct them and resubmit the command, or you can restore the state of the database using the Transaction object’s RollBack method. If no errors occur, you can make the changes permanent by calling the transaction object’s Commit method.

17.Explain why exception handling is important to a completed application.
When an unhandled exception occurs in an application, the application stops—the user can’t proceed, and any work he or she did immediately prior to the exception is lost. Exception handling provides a way to intercept and correct unusual occurrences that would otherwise cause these problems.

18.List two different exception-handling approaches in ASP.NET Web applications.
Exceptions can be handled in exception-handling blocks using the Try, Catch, and Finally keywords in Visual Basic .NET or the try, catch, and finally keywords in Visual C#. They can also be handled using Error event procedures at the Global, Application, or Page levels using the Server object’s GetLastError and ClearError methods.

19.Describe the purpose of error pages and why they are needed.
Because Web applications run over the Internet, some exceptions occur outside the scope of the application. This means that your application can’t respond directly to these exceptions. These types of exceptions are identified by HTTP response codes, which IIS can respond to by displaying custom error pages listed in your application’s Web.config file.

20.Explain why tracing helps with exception handling.
Tracing allows you to record unusual events while your application is running, without users being aware of it. If an unanticipated exception occurs, your application can write a message to the trace log, which helps you diagnose problems during testing and after deployment.

21.How do you call a stored procedure?
Create a command object, set the object’s CommandText property to the name of the stored procedure, and set the CommandType property to StoredProcedure. To execute the stored procedure, use the command object’s ExecuteNonQuery, ExcecuteScalar, ExecuteReader, or ExecutelXmlReader method. For example, the following code calls the Ten Most Expensive

Products stored procedure on the Northwind Traders database:
// Create a connection for NorthWind Trader's database.
SqlConnection connNWind = new SqlConnection("integrated security=SSPI;" +
"data source=(local);initial catalog=Northwind");
// Create a command object to execute.
SqlCommand cmdTopTen = new SqlCommand(connNWind);
cmdTopTen.CommandText = "Ten Most Expensive Products";
// Set the command properties.
cmdTopTen.CommandType = CommandType.StoredProcedure;
// Create a data reader object to get the results.
SqlDataReader drdTopTen;
// Open the connection.
// Excecute the stored procedure.
drdTopTen = cmdTopTen.ExecuteReader();

C# .NET interview questions

1.Does C# support multiple-inheritance?

2.Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

3.Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

4.Describe the accessibility modifier “protected internal”.
It is available to classes that are within the same assembly and derived from the specified base class.

5.What’s the top .NET class that everything is derived from?

6.What does the term immutable mean?
The data value may not be changed. Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

7.What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

8.What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

9.Can you store multiple data types in System.Array?

10.What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

11.How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

12.What’s the .NET collection class that allows an element to be accessed using a unique key?

13.What class is underneath the SortedList class?
A sorted HashTable.

14.Will the finally block get executed if an exception has not occurred?­

15.What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

16.Can multiple catch blocks be executed for a single try statement?
No. Once the proper catch block processed, control is transferred to the finally block .

17.Explain the three services model commonly know as a three-tier application.
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

Class Questions

1.What is the syntax to inherit from a class in C#?
Place a colon and then the name of the base class.
Example: class MyNewClass : MyBaseClass

2.Can you prevent your class from being inherited by another class?
Yes. The keyword “sealed” will prevent the class from being inherited.

3.Can you allow a class to be inherited, but prevent the method from being over-ridden?
Yes. Just leave the class public and make the method sealed.

4.What’s an abstract class?
A class that cannot be instantiated. An abstract class is a class that must be inherited and have the methods overridden. An abstract class is essentially a blueprint for a class without any implementation.

5.When do you absolutely have to declare a class as abstract?
1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2. When at least one of the methods in the class is abstract.

6.What is an interface class?
Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes.

7.Why can’t you specify the accessibility modifier for methods inside the interface?
They all must be public, and are therefore public by default.

8.Can you inherit multiple interfaces?
Yes. .NET does support multiple interfaces.

9.What’s the difference between an interface and abstract class?
In an interface class, all methods are abstract - there is no implementation. In an abstract class some methods can be concrete. In an interface class, no accessibility modifiers are allowed. An abstract class may have accessibility modifiers.

10.What is the difference between a Struct and a Class?
Structs are value-type variables and are thus saved on the stack, additional overhead but faster retrieval. Another difference is that structs cannot inherit.

Method and Property Questions

1.What’s the implicit name of the parameter that gets passed into the set method/property of a class?
Value. The data type of the value parameter is defined by whatever data type the property is declared as.

2.What does the keyword “virtual” declare for a method or property?
The method or property can be overridden.

3.How is method overriding different from method overloading?
When overriding a method, you change the behavior of the method for the derived class. Overloading a method simply involves having another method with the same name within the class.

4.Can you declare an override method to be static if the original method is not static?
No. The signature of the virtual method must remain the same. (Note: Only the keyword virtual is changed to keyword override)

5.What are the different ways a method can be overloaded?
Different parameter data types, different number of parameters, different order of parameters.

6.If a base class has a number of overloaded constructors, and an inheriting class has a number of overloaded constructors; can you enforce a call from an inherited constructor to a specific base constructor?
Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

Events and Delegates

1.What’s a delegate?
A delegate object encapsulates a reference to a method.

2.What’s a multicast delegate?
A delegate that has multiple handlers assigned to it. Each assigned handler (method) is called.

XML Documentation Questions

1.Is XML case-sensitive?

2.What’s the difference between // comments, /* */ comments and /// comments?
Single-line comments, multi-line comments, and XML documentation comments.

3.How do you generate documentation from the C# file commented properly with a command-line compiler?
Compile it with the /doc switch.

Debugging and Testing Questions

1.What debugging tools come with the .NET SDK?
1. CorDBG – command-line debugger. To use CorDbg, you must compile the original C# file using the /debug switch.
2. DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR.

2.What does assert() method do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.

3.What’s the difference between the Debug class and Trace class?
Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

4.Why are there five tracing levels in System.Diagnostics.TraceSwitcher?
The tracing dumps can be quite verbose. For applications that are constantly running you run the risk of overloading the machine and the hard drive. Five levels range from None to Verbose, allowing you to fine-tune the tracing activities.

5.Where is the output of TextWriterTraceListener redirected?
To the Console or a text file depending on the parameter passed to the constructor.

6.How do you debug an ASP.NET Web application?
Attach the aspnet_wp.exe process to the DbgClr debugger.

7.What are three test cases you should go through in unit testing?
1. Positive test cases (correct data, correct output).
2. Negative test cases (broken or missing data, proper handling).
3. Exception test cases (exceptions are thrown and caught properly).

8.Can you change the value of a variable while debugging a C# application?
Yes. If you are debugging via Visual Studio.NET, just go to Immediate window.

ADO.NET and Database Questions

1.What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.

2.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.

3.What is the wildcard character in SQL?
Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.

4.Explain ACID rule of thumb for transactions.
A transaction must be:
1. Atomic - it is one unit of work and does not dependent on previous and following transactions.
2. Consistent - data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t.
3. Isolated - no transaction sees the intermediate results of the current transaction).
4. Durable - the values persist if the data had been committed even if the system crashes right after.

5.What connections does Microsoft SQL Server support?
Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and password).

6.Between Windows Authentication and SQL Server Authentication, which one is trusted and which one is untrusted?
Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.

7.What does the Initial Catalog parameter define in the connection string?
The database name to connect to.

8.What does the Dispose method do with the connection object?
Deletes it from the memory.
To Do: answer better. The current answer is not entirely correct.

9.What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.

Assembly Questions

1.How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

2.What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.

3.What is a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.

4.What namespaces are necessary to create a localized application?
System.Globalization and System.Resources.

5.What is the smallest unit of execution in .NET?
an Assembly.

6.When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.

7.How do you convert a value-type to a reference-type?
Use Boxing.

8.What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.

Monday, June 22, 2009

Servlet Interview Questions

1.What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

2.When doGET() method will going to execute?
When we specified method=’GET’ in HTML
Example : < name="’SSS’" method="’GET’">
When doPOST() method will going to execute?
When we specified method=’POST’ in HTML
< name="’SSS’" method="’POST’">

3.What is the difference between Difference between doGet() and doPost()?
GET Method : Using get method we can able to pass 2K data from HTML
All data we are passing to Server will be displayed in URL (request string).

POST Method : In this method we does not have any size limitation.
All data passed to server will be hidden, User cannot able to see this info
on the browser.

4.What is the servlet life cycle?
When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method

5.What is the servlet?
Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming we will use java language. A servlet can handle multiple requests concurrently

6.What is the architechture of servlet package?
Servlet Interface is the central abstraction. All servlets implements this Servlet
Interface either direclty or indirectly
( may implement or extend Servlet Interfaces sub classes or sub interfaces)

Generic Servlet
HttpServlet ( Class ) — we will extend this class to handle GET / PUT HTTP requests

7.What is the difference between HttpServlet and GenericServlet?
A GenericServlet has a service() method to handle requests.
HttpServlet extends GenericServlet added new methods
doTrace() methods
Both these classes are abstract.

8.What’s the difference between servlets and applets?
Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.
What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?
The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

9.What is the use of ServletContext ?
Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.
Is there any way to generate PDF’S dynamically in servlets?
We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

10.What is the difference between using getSession(true) and getSession(false) methods?
getSession(true) - This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.

getSession(false) - This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

11.Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set.

12.Which protocol will be used by browser and servlet to communicate ?

13.In how many ways we can track the sessions?
Method 1) By URL rewriting

Method 2) Using Session object

Getting Session form HttpServletRequest object
HttpSession session = request.getSession(true);

Get a Value from the session

Adding values to session
cart = new Cart();
session.putValue(session.getId(), cart);

At the end of the session, we can inactivate the session by using the following command

Method 3) Using cookies

Method 4) Using hidden fields

14.How Can You invoke other web resources (or other servlet / jsp ) ?
Servelt can invoke other Web resources in two ways: indirect and direct.

Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)

Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.

You can get this object using getRequestDispatcher(”URL”) method. You can get this object from either a request or a Context.

Example :
RequestDispatcher dispatcher = request.getRequestDispatcher(”/jspsample.jsp”);
if (dispatcher != null)
dispatcher.forward(request, response);

15.How Can you include other Resources in the Response?
Using include method of a RequestDispatcher object.

Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.

Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(”/banner”);
if (dispatcher != null)
dispatcher.include(request, response);

16.What is the difference between the getRequestDispatcher(String path) ServletRequest interface and ServletContext interface?

The getRequestDispatcher(String path) method of ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of ServletContext interface cannot accepts relative paths. All path must sart with a “/” and are interpreted as relative to curent context root. If the resource is not available, or if the server has not implemented a RequestDispatcher object for that type of resource, getRequestDispatcher will return null. Your servlet should be prepared to deal with this condition.

Sunday, June 21, 2009

J2EE Interview Questions

1.What do you understand by a J2EE module?
A J2EE module is a software unit that consists of one or more J2EE components of the same container type along with one deployment descriptor of that type. J2EE specification defines four types of modules:
a) EJB
b) Web
c) application client and
d) resource adapter

In the J2EE applications modules can be deployed as stand-alone units. Modules can also be assembled into J2EE applications.

2.What are the contents of web module?
A web module may contain:
a) JSP files
b) Java classes
c) gif and html files and
d) web component deployment descriptors

3.Differentiate between .ear, .jar and .war files.
These files are simply zipped file using java jar tool. These files are created for different purposes. Here is the description of these files:
.jar files: These files are with the .jar extenstion. The .jar files contains the libraries, resources and accessories files like property files.
.war files: These files are with the .war extension. The war file contains the web application that can be deployed on the any servlet/jsp container. The .war file contains jsp, html, javascript and other files for necessary for the development of web applications.
.ear files: The .ear file contains the EJB modules of the application.

4.What is the difference between Session Bean and Entity Bean?
Session Bean: Session is one of the EJBs and it represents a single client inside the Application Server. Stateless session is easy to develop and its efficient. As compare to entity beans session beans require few server resources.

A session bean is similar to an interactive session and is not shared; it can have only one client, in the same way that an interactive session can have only one user. A session bean is not persistent and it is destroyed once the session terminates.

Entity Bean: An entity bean represents persistent global data from the database. Entity beans data are stored into database.

5.Why J2EE is suitable for the development distributed multi-tiered enterprise applications?
The J2EE platform consists of multi-tiered distributed application model. J2EE applications allows the developers to design and implement the business logic into components according to business requirement. J2EE architecture allows the development of multi-tired applications and the developed applications can be installed on different machines depending on the tier in the multi-tiered J2EE environment . The J2EE application parts are:

a) Client-tier components run on the client machine.
b) Web-tier components run on the J2EE server.
c) Business-tier components run on the J2EE server and the
d) Enterprise information system (EIS)-tier software runs on the EIS servers

6.What are the services provided by a container?
The services provided by container are as follows:
a) Transaction management for the bean
b) Security for the bean
c) Persistence of the bean
d) Remote access to the bean
e) Lifecycle management of the bean
f) Database-connection pooling
g) Instance pooling for the bean

7.What are types of J2EE clients?
J2EE clients are the software that access the services components installed on the J2EE container. Following are the J2EE clients:
a) Applets
b) Java-Web Start clients
c) Wireless clients
d) Web applications

8.What do you understand by JTA and JTS?
JTA stands for Java Transaction API and JTS stands for Java Transaction Service. JTA provides a standard interface which allows the developers to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK uses the JTA transaction manager to implement the transaction. The code developed by developers does not calls the JTS methods directly, but only invokes the JTA methods. Then JTA internally invokes the JTS routines. JTA is a high level transaction interface used by the application code to control the transaction.

9.What is JAXP?
The Java API for XML Processing (JAXP) enables applications to parse and transform XML documents independent of a particular XML processing implementation. JAXP or Java API for XML Parsing is an optional API provided by Javasoft. It provides basic functionality for reading, manipulating, and generating XML documents through pure Java APIs. It is a thin and lightweight API that provides a standard way to seamlessly integrate any XML-compliant parser with a Java application.

10.What is difference between Java Bean and Enterprise Java Bean?
Java Bean as is a plain java class with member variables and getter setter methods. Java Beans are defined under JavaBeans specification as Java-Based software component model which includes the features like introspection, customization, events, properties and persistence.

Enterprise JavaBeans or EJBs for short are Java-based software components that comply with Java’s EJB specification. EJBs are delpoyed on the EJB container and executes in the EJB container. EJB is not that simple, it is used for building distributed applications. Examples of EJB are Session Bean, Entity Bean and Message Driven Bean. EJB is used for server side programming whereas java bean is a client side. Bean is only development but the EJB is developed and then deploy on EJB Container.

11.Can Entity Beans have no create() methods?
Entity Beans can have no create() methods. Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database.

12.What are the call back methods in Session bean?
Callback methods are called by the container to notify the important events to the beans in its life cycle. The callback methods are defined in the javax.ejb.EntityBean interface.The callback methods example are ejbCreate(), ejbPassivate(), and ejbActivate().

JSP interview Questions

1. What is JSP?
JSP Stands for Java server pages. JSP is Java technology which is used by developers across the world to create dynamically generated websites with the easy use of other documents like HTML, XML. This technology of java allows developers to include java code and some pre defined actions into static content. Java server pages are compiled into java servlet by the java compiler or the java compiler may directly generate the byte code for the servlet.

2. How servlet differ from JSP?
Both Servlet and Java Server Pages are API which generate dynamic web content. A servlet is nothing but a java class which implements the interface to run within a web and on the other hand Java server pages is a bit complicated thing which contain a mixture of Java scripts, Java directives, Java elements and HTML. The main difference among both servlet and Java server pages is that JSP is document oriented and servlet on the other hand act likes a program.

3. What are the advantages of JSP?
There are many advantages of JSP and JSP is very much preferred by every coder. The main advantage of JSP over anything is its auto compilation and the length of code is reduced by using custom tags and tag library. Secondly, it is portable that is it works on all operating system and non – Microsoft web servers. Java components can be easily embedded into the dynamic pages. JSP have all the features of java and can easily separate dynamic part from the static part of the page.

4. What are the implicit objects in JSP?
There are all total 9 implicit objects in JSP. Application interface refers to the web application’s interface whereas Session interface refers to the user’s session. Request interface refers to the page which is currently requested whereas Response interface refers to the response which is currently made by the user. Config interface refers to the servlet configuration. Class like out, page, page Context and exception refers to the output stream of the page, servlet instance of the page, environment of the page, error handling respectively.

5. How JSP calls a stored procedure?
Java Server Pages possess all the characteristics of java and to call and have similar syntax to call a function. Functions and stored procedures of a database can be called by using the statement callable. Another way to call the stored procedure is by writing the JDBC code in between the tag of scriptlet tab.write.

6.What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.

1.Page translation: -page is parsed, and a java file which is a servlet is created.
2.Page compilation: page is compiled into a class file
3.Page loading : This class file is loaded.
4.Create an instance :- Instance of servlet is created
5.jspInit() method is called
6._jspService is called to handle service calls
7._jspDestroy is called to destroy it when the servlet is not required.

7.Why are JSP pages the preferred API for creating a web-based client program?
Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

8.Is JSP technology extensible?
Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.

9.How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %>redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

10. How do we use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone.
The following example shows the “today” property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action.

"><%-- scriptlets calling bean setter methods go here --%>

11.What are custom tags and why it is needed?
JSP tags are extended by creating a custom set of tags which is called as tag library (taglib). The page which uses custom tags declares taglib and uniquely names, defines and associates a tag prefix to differentiate the usage of those tags.

12.How cookies is deleted in JSP?
There are two ways by which the cookies can be deleted in JSP. Firstly, by setting the setMaxAge() of the cookie class to zero. And secondly by setting a timer in the header file that is response. setHeader(expires {Mention the time} attribute), which will delete the cookies after that prescribed time.

13.Is it possible by a JSP page to process HTML form data?
Yes ,it is possible by simply obtaining the data from the FORM input via the request implicit object which lies with a scriptlet or expression but it doesn't require to implement any HTTP – Protocol methods like goGet() or doPost() within the JSP page.

Friday, June 19, 2009


What is LDAP?

LDAP, Lightweight Directory Access Protocol, is an Internet protocol that email and other programs use to look up information from a server.

This is an application protocol for querying and modifying directory services running over TCP/IP.

Key aspects of LDAP are:

- Protocol elements are carried directly over TCP or other transport,
bypassing much of the session/presentation overhead.

- Many protocol data elements are encoding as ordinary strings (e.g.,
Distinguished Names).

- A lightweight BER encoding is used to encode all protocol elements.

What is Active Directory?

An active directory is a directory structure used on Microsoft Windows based computers and servers to store information and data about networks and domains. It is primarily used for online information and was originally created in 1996 and first used with Windows 2000.

An active directory (sometimes referred to as an AD) does a variety of functions including the ability to provide information on objects, helps organize these objects for easy retrieval and access, allows access by end users and administrators and allows the administrator to set security up for the directory.

An active directory can be defined as a hierarchical structure and this structure is usually broken up into three main categories, the resources which might include hardware such as printers, services for end users such as web email servers and objects which are the main functions of the domain and network.

If you are a computer administrator for a large corporation or organization, you can easily update all end users computers with new software, patches, files, etc simply by updating one object in a forest or tree.

Access to information stored in Active Directory is available using standard Active Directory management utilities. They are convenient and fairly easy to use; however, there are situations in which you might want to develop alternative, custom solutions. For example, you might want to quickly access user or group account information from any workstation in your environment.

Technical Details To Access Active Directory via ASP (vb script)

The script below, ListADGroups.vbs, uses Active Data Objects (and an underlying OLE DB Directory Services provider called ADsDSOObject) to extract a list of groups from Active Directory. This involves creating the following ADO objects:

* A Connection object stored in oCon variable,
* A Command object stored in oCmd variable,
* A RecordSet object, stored in oRecordSet variable.

For each of these objects, we set appropriate properties. More specifically, for the Connection object:

* Provider property determines OLE DB provider used for connection to Active Directory (ADSDSOObject)
* sUser variable is the name of the domain user that will be used to connect to Active Directory (replace this value with an actual user name in your domain)
* sPassword variable is a password for the sUser account (set it appropriately as well)

For the Command Object:

* ActiveConnection property is set to the previously created oCon object
* CommandText property consists of semicolon-separated search parameters. The scope is determined by the first parameter, which contains, in this case, the LDAP path of the target domain. The second parameter contains search criteria. objectCategory determines the type of object to search for (groups in our case). The objects are filtered according to the value of the sGroup variable. For example, in order to return all the groups with names that start with the "US" prefix, you would set sGroup to "US*". The value of "*" used in the script returns all the groups within the scope determined by the first parameter (domain in this case). Object properties to be returned are listed in the third parameter (and include group name, LDAP path, description, and group members). Finally, the last parameter specifies search depth (in the hierarchy of Active Directory containers) -- all directory objects in our case.

The outcome of running the Execute method of the ADO Command object is stored in the RecordSet. In order to retrieve the results, the script traverses it record by record and displays contents of each one.

Check Out the Function to Query The Active Directory using LDAP into a recordset

Sub GetDisplayName()

Dim conn
Dim com
Dim oRecordset

'* Open the connection to AD *

Set conn = CreateObject("ADODB.Connection")
conn.Provider = "ADsDSOObject"
conn.Properties("User ID") = "Dir Mgr"
conn.Properties("Password") = "MyPassword"

conn.Open "LDAP Provider"

Set com = CreateObject("ADODB.Command")
com.ActiveConnection = conn

com.CommandText = "SELECT displayName FROM 'LDAP://MyHost:477/OU=abc,DC=ad,DC=mhkk,DC=com'"

oRecordset = com.Execute

end sub

Thursday, June 18, 2009

Delegates and Events in C#.Net

Delegates in C# .Net:

If we look at C++ there is a feature called callback function. This feature uses Pointers to Functions to pass them as parameters to other functions. Delegate is a similar feature but it is more type safe, which stands as a stark contrast with C++ function pointers. A delegate can hold reference/s to one more more functions and invoke them as and when needed.

A delegate needs the method's name and its parameters (input and output variables) when we create a delegate. But delegate is not a standalone construction. it's a class. Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.

If the delegate contains a return type of void, then it is automatically aliased to the type of System.MulticastDelegate. This can support multiple functions with a += operator. If the delegate contains a non-void return type then it is aliased to System.Delegate class and it cannot support multiple methods.

A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# but can be used in a context removed from event handling (e.g. passing a method to a method through a delegate parameter).


public delegate int DelegateMethod(int x, int y);

Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate. This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own-delegated method.

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.

Delegate magic :

In class we create its object, which is instance, but in delegate when we create instance that is also referred as delegate (means whatever you do you will get delegate).

Delegate does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

Benefit of delegates:
In simple words delegates are object oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegate helps in code optimization.

Types of delegates:

1) Singlecast delegates

2) Multiplecast delegates

Delegate is a class. Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.

Singlecast delegate
Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class.

Multicast Delegate

When a delegate is wrapped with more than one method that is known as a multicast delegate.

In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from System.MulticastDelegate class.

Events in C# .Net:

Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net. Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.) or any event triggered by the program .

Event and delegate are linked together. Event is a reference of delegate i.e. when event will be raised delegate will be called. In C# terms, events are a special form of delegate. Events are nothing but change of state. Events play an important part in GUI programming. Events and delegates work hand-in-hand to provide a program's functionality. A C# event is a class member that is activated whenever the event it was designed for occurs.

It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The event keyword is a delegate modifier. It must always be used in connection with a delegate.

The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.


obj.MyEvent += new MyDelegate(obj.Display);

An event has the value null if it has no registered listeners. Although events are mostly used in Windows controls programming, they can also be implemented in console, web and other applications.

Tuesday, June 16, 2009

EJB: Interview Questions

1.Are enterprise beans allowed to use Thread.sleep()?

Enterprise beans make use of the services provided by the EJB container, such as life-cycle management. To avoid conflicts with these services, enterprise beans are restricted from performing certain operations: Managing or synchronizing threads .

2.Is it possible to write two EJB’s that share the same Remote and Home interfaces, and have different bean classes? if so, what are the advantages/disadvantages?

It’s certainly possible. In fact, there’s an example that ships with the Inprise Application Server of an Account interface with separate implementations for CheckingAccount and SavingsAccount, one of which was CMP and one of which was BMP.

3.Is it possible to specify multiple JNDI names when deploying an EJB?

No. To achieve this you have to deploy your EJB multiple times each specifying a different JNDI name.

4.Can an EJB send asynchronous notifications to its clients?

Asynchronous notification is a known hole in the first versions of the EJB spec. The recommended solution to this is to use JMS, which is becoming available in J2EE-compliant servers. The other option, of course, is to use client-side threads and polling. This is not an ideal solution, but it’s workable for many scenarios.

5.How can I access EJB from ASP?

You can use the Java 2 Platform, Enterprise Edition Client Access Services (J2EETM CAS) COMBridge 1.0, currently downloadable from Sun.

6.Is there a guarantee of uniqueness for entity beans?

There is no such guarantee. The server (or servers) can instantiate as many instances of the same underlying Entity Bean (with the same PK) as it wants. However, each instance is guaranteed to have up-to-date data values, and be transactionally consistent, so uniqueness is not required. This allows the server to scale the system to support multiple threads, multiple concurrent requests, and multiple hosts.

7.How do the six transaction attributes map to isolation levels like “dirty read”? Will an attribute like “Required” lock out other readers until I’m finished updating?

The Transaction Attributes in EJB do not map to the Transaction Isolation levels used in JDBC. This is a common misconception. Transaction Attributes specify to the container when a Transaction should be started, suspended(paused) and committed between method invocations on Enterprise JavaBeans. For more details and a summary of Transaction Attributes refer to section 11.6 of the EJB 1.1 specification.

8.Can the primary key in the entity bean be a Java primitive type such as int?

The primary key can’t be a primitive type–use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive)

9.What’s new in the EJB 2.0 specification?

Following are the main features supported in EJB 2.0: Integration of EJB with JMS, Message Driven Beans, Implement additional Business methods in Home interface which are not specific for bean instance, EJB QL.

10.How many types of protocol implementations does RMI have?

RMI has at least three protocol implementations: Java Remote Method Protocol(JRMP), Internet Inter ORB Protocol(IIOP), and Jini Extensible Remote Invocation(JERI). These are alternatives, not part of the same thing, All three are indeed layer 6 protocols for those who are still speaking OSI reference model.

11.What is the need of Remote and Home interfaces. Why can’t there be one?

In a few words, I would say that the main reason is because there is a clear division of roles and responsabilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsable of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and the beans) and you need two different interfaces for accessing to both of them.

12.What is the difference between Java Beans and EJB?

Java Beans are client-side objects and EJBs are server side object, and they have completely different development, lifecycle, purpose.

13.Does EJB 1.1 support mandate the support for RMI-IIOP ? What is the meaning of “the client API must support the Java RMI-IIOP programming model for portability, but the underlying protocol can be anything” ?

EJB1.1 does mandate the support of RMI-IIOP. There are 2 types of implementations that an EJB Server might provide: CORBA-based EJB Servers and Proprietry EJB Servers. Both support the RMI-IIOP API but how that API is implemented is a different story. (NB: By API we mean the interface provided to the client by the stub or proxy). A CORBA-based EJB Server actually implements its EJB Objects as CORBA Objects (it therefore encorporates an ORB and this means that EJB’s can be contacted by CORBA clients (as well as RMI-IIOP clients) A proprietry EJB still implements the RMI-IIOP API (in the client’s stub) but the underlying protocol can be anything. Therefore your EJB’s CANNOT be contacted by CORBA clients. The difference is that in both cases, your clients see the same API (hence, your client portability) BUT how the stubs communicate with the server is different.

14.What is clustering? What are the different algorithms used for clustering?

Clustering is grouping machines together to transparantly provide enterprise services.The client does not now the difference between approaching one server or approaching a cluster of servers.Clusters provide two benefits: scalability and high availability. Further information can be found in the JavaWorld article J2EE Clustering.

15.What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?
Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean – Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean – The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container. But in case of JDBC you have to explicitly do the above features. what suresh told is exactly perfect. ofcourse, this comes under the database transations, but i want to add this. the great thing about the entity beans of container managed, whenever the connection is failed during the transaction processing, the database consistancy is mantained automatically. the container writes the data stored at persistant storage of the entity beans to the database again to provide the database consistancy. where as in jdbc api, we, developers has to do manually.

16.What is the role of serialization in EJB?

A big part of EJB is that it is a framework for underlying RMI: remote method invocation. You’re invoking methods remotely from JVM space ‘A’ on objects which are in JVM space ‘B’ — possibly running on another machine on the network. To make this happen, all arguments of each method call must have their current state plucked out of JVM ‘A’ memory, flattened into a byte stream which can be sent over a TCP/IP network connection, and then deserialized for reincarnation on the other end in JVM ‘B’ where the actual method call takes place. If the method has a return value, it is serialized up for streaming back to JVM A. Thus the requirement that all EJB methods arguments and return values must be serializable. The easiest way to do this is to make sure all your classes implement

17.What is EJB QL?

EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

ASP.NET : Interview Questions

1.Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process?
inetinfo.exe is theMicrosoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request tothe actual worker process aspnet_wp.exe.

2.What’s the difference between Response.Write() andResponse.Output.Write()?
Response.Output.Write() allows you to write formatted output.

3.What methods are fired during the page load?
Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.

4.When during the page processing cycle is ViewState available?
After the Init() and before the Page_Load(), or OnLoad() for a control.

5.What namespace does the Web page belong in the .NET Framework class hierarchy?

6.Where do you store the information about the user’s locale?

7.What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?
CodeBehind is relevant to Visual Studio.NET only.

8.What’s a bubbled event?
When you have a complex control, like DataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.

9.Suppose you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?
Add an OnMouseOver attribute to the button. Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

10.What data types do the RangeValidator control support?
Integer, String, and Date.

11.Explain the differences between Server-side and Client-side code?
Server-side code executes on the server. Client-side code executes in the client's browser.

12.What type of code (server or client) is found in a Code-Behind class?
The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

13.Should user input data validation occur server-side or client-side? Why?
All user input data validation should occur on the server at a minimum. Additionally, client-side validation can be performed where deemed appropriate and feasable to provide a richer, more responsive experience for the user.

14What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?
Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

15.Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
Valid answers are:
· A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
· A DataSet is designed to work without any continuing connection to the original data source.
· Data in a DataSet is bulk-loaded, rather than being loaded on demand.
· There's no concept of cursor types in a DataSet.
· DataSets have no current record pointer You can use For Each loops to move through the data.
· You can store many edits in a DataSet, and write them to the original data source in a single operation.
· Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.

16.What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.

17.What are the Application_Start and Session_Start subroutines used for?
This is where you can set the specific variables for the Application and Session objects.

18.Can you explain what inheritance is and an example of when you might use it?
When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

19.Whats an assembly?
Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

20.Describe the difference between inline and code behind?
Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

21.Explain what a diffgram is, and a good use for one?
The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

22.Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

23.Which method do you invoke on the DataAdapter control to load your generated dataset with data?
The Fill() method.

24.Can you edit data in the Repeater control?
No, it just reads the information from its data source.

25.Which template must you provide, in order to display data in a Repeater control?

26.How can you provide an alternating color scheme in a Repeater control?
Use the AlternatingItemTemplate.

27.What property must you set, and what method must you call in your code, in order to bind the data from a data source to the Repeater control?
You must set the DataSource property and call the DataBind method.

28.What base class do all Web Forms inherit from?
The Page class.

29.Name two properties common in every validation control?
ControlToValidate property and Text property.

30.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.

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

32.How many classes can a single .NET DLL contain?
It can contain many classes.

33.Difference between Application and Session Events
The ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:
Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request.
Session events are similar to application events (there is a Session_OnStart and a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.
You can create handlers for these types of events in the Global.asax file.

34. Difference between ASP Session and ASP.NET Session? session supports cookie less session & it can span across multiple servers.

35. What is cookie less session? How it works?
By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following:

36. How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are the limits?
By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session data in an external process, which can even reside on another machine. To enable this feature:
Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters\Port
Set the mode attribute of the section to "StateServer".
Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state.
The following sample assumes that the state service is running on the same machine as the Web server ("localhost") and uses the default port (42424):

37. What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state?

Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip.
To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips.
However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support
38. What are the disadvantages of view state / what are the benefits?
Automatic view-state management is a feature of server controls that enables them to repopulate their property values on a round trip (without you having to write any code). This feature does impact performance, however, since a server control's view state is passed to and from the server in a hidden form field. You should be aware of when view state helps you and when it hinders your page's performance.

39. When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade?

Maintaining state using database technology is a common practice when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted.

40.What type of code (server or client) is found in a Code-Behind class?

41.Should validation (did the user enter a real date) occur server-side or client-side? Why?
Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.

42.What are ASP.NET Web Forms? How is this technology different than what is available though ASP?
Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

43.What base class do all Web Forms inherit from?

44.How do you turn off cookies for one page in your site?
Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.

45.Which two properties are on every validation control?
ControlToValidate & ErrorMessage properties

46.How do you create a permanent cookie?
Setting the Expires property to MinValue means that the Cookie never expires.

47.What does WSDL stand for?

Web Services Description Language

48.What tags do you need to add within the asp:datagrid tags to bind columns manually?
Column tag and an ASP:databound tag.