Sunday, April 26, 2009

Basic shell scripting questions

Question: How do you find out what’s your shell? - echo $SHELL

Question: What’s the command to find out today’s date? - date

Question: What’s the command to find out users on the system? - who

Question: How do you find out the current directory you’re in? - pwd

Question: How do you remove a file? - rm

Question: How do you remove a - rm -rf

Question: How do you find out your own username? - whoami

Question: How do you send a mail message to somebody? - mail -s ‘Your subject’ -c ‘‘

Question: How do you count words, lines and characters in a file? - wc

Question: How do you search for a string inside a given file? - grep string filename

Question: How do you search for a string inside a directory? - grep string *

Question: How do you search for a string in a directory with the subdirectories recursed? - grep -r string *

Question: What are PIDs? - They are process IDs given to processes. A PID can vary from 0 to 65535.

Question: How do you list currently running process? - ps

Question: How do you stop a process? - kill pid

Question: How do you find out about all running processes? - ps -ag

Question: How do you stop all the processes, except the shell window? - kill 0

Question: How do you fire a process in the background? - ./process-name &

Question: How do you refer to the arguments passed to a shell script? - $1, $2 and so on. $0 is your script name.

Question: What’s the conditional statement in shell scripting? - if {condition} then … fi

Question: How do you do number comparison in shell scripts? - -eq, -ne, -lt, -le, -gt, -ge

Question: How do you test for file properties in shell scripts? - -s filename tells you if the file is not empty, -f filename tells you whether the argument is a file, and not a directory, -d filename tests if the argument is a directory, and not a file, -w filename tests for writeability, -r filename tests for readability, -x filename tests for executability

Question: How do you do Boolean logic operators in shell scripting? - ! tests for logical not, -a tests for logical and, and -o tests for logical or.

Question: How do you find out the number of arguments passed to the shell script? - $#

Question: What’s a way to do multilevel if-else’s in shell scripting? - if {condition} then {statement} elif {condition} {statement} fi

Question: How do you write a for loop in shell? - for {variable name} in {list} do {statement} done

Question: How do you write a while loop in shell? - while {condition} do {statement} done

Question: How does a case statement look in shell scripts? - case {variable} in {possible-value-1}) {statement};; {possible-value-2}) {statement};; esac

Question: How do you read keyboard input in shell scripts? - read {variable-name}

Question: How do you define a function in a shell script? - function-name() { #some code here return }

Question: How does getopts command work? - The parameters to your script can be passed as -n 15 -x 20. Inside the script, you can iterate through the getopts array as while getopts n:x option, and the variable $option contains the value of the entered option.

Linux command line Q and A Questions

Question: You need to see the last fifteen lines of the files dog, cat and horse. What command should you use?
tail -15 dog cat horse
The tail utility displays the end of a file. The -15 tells tail to display the last fifteen lines of each specified file.

Question: Who owns the data dictionary?
The SYS user owns the data dictionary. The SYS and SYSTEM users are created when the database is created.

Question: You routinely compress old log files. You now need to examine a log from two months ago. In order to view its contents without first having to decompress it, use the _________ utility.

The zcat utility allows you to examine the contents of a compressed file much the same way that cat displays a file.

Question: You suspect that you have two commands with the same name as the command is not producing the expected results. What command can you use to determine the location of the command being run?
The which command searches your path until it finds a command that matches the command you are looking for and displays its full path.
You locate a command in the /bin directory but do not know what it does. What command can you use to determine its purpose.
The whatis command displays a summary line from the man page for the specified command.
You wish to create a link to the /data directory in bob’s home directory so you issue the command ln /data /home/bob/datalink but the command fails. What option should you use in this command line to be successful.
Use the -F option
In order to create a link to a directory you must use the -F option.

Question: When you issue the command ls -l, the first character of the resulting display represents the file’s ___________.
The first character of the permission block designates the type of file that is being displayed.

Question: What utility can you use to show a dynamic listing of running processes?
The top utility shows a listing of all running processes that is dynamically updated.

Question: Where is standard output usually directed?
to the screen or display
By default, your shell directs standard output to your screen or display.

Question: You wish to restore the file memo.ben which was backed up in the tarfile MyBackup.tar. What command should you type?
tar xf MyBackup.tar memo.ben
This command uses the x switch to extract a file. Here the file memo.ben will be restored from the tarfile MyBackup.tar.

Question: You need to view the contents of the tarfile called MyBackup.tar. What command would you use?
tar tf MyBackup.tar
The t switch tells tar to display the contents and the f modifier specifies which file to examine.

Question: You want to create a compressed backup of the users’ home directories. What utility should you use?
You can use the z modifier with tar to compress your archive at the same time as creating it.

Question: What daemon is responsible for tracking events on your system?
The syslogd daemon is responsible for tracking system information and saving it to specified log files.

Question: You have a file called phonenos that is almost 4,000 lines long. What text filter can you use to split it into four pieces each 1,000 lines long?
The split text filter will divide files into equally sized pieces. The default length of each piece is 1,000 lines.

Question: You would like to temporarily change your command line editor to be vi. What command should you type to change it?
set -o vi
The set command is used to assign environment variables. In this case, you are instructing your shell to assign vi as your command line editor. However, once you log off and log back in you will return to the previously defined command line editor.

Question: What account is created when you install Linux?
Whenever you install Linux, only one user account is created. This is the superuser account also known as root.

Question: What command should you use to check the number of files and disk space used and each user’s defined quotas?
The repquota command is used to get a report on the status of the quotas you have set including the amount of allocated space and amount of used space.

Solaris interview questions

Question: List the files in current directory sorted by size ?
Answer: - ls -l | grep ^- | sort -nr

Question: List the hidden files in current directory ?
Answer: - ls -a1 | grep "^\."

Question: Delete blank lines in a file ?
Answer: - cat sample.txt | grep -v ‘^$’ > new_sample.txt

Question: Search for a sample string in particular files ?
Answer: - grep “Debug” *.confHere grep uses the string “Debug” to search in all files with extension“.conf” under current directory.

Question: Display the last newly appending lines of a file during appendingdata to the same file by some processes ? - tail –f Debug.logHere tail shows the newly appended data into Debug.log by some processes/user.

Question: Display the Disk Usage of file sizes under each directory in currentDirectory ? - du -k * | sort –nr (or) du –k . | sort -nr
Change to a directory, which is having very long name ? - cd CDMA_3X_GEN*Here original directory name is – “CDMA_3X_GENERATION_DATA”.

Question: Display the all files recursively with path under current directory ? - find . -depth -print

Question: Set the Display automatically for the current new user ?
Answer: - export DISPLAY=`eval ‘who am i | cut -d"(" -f2 | cut -d")" -f1′`Here in above command, see single quote, double quote, grave ascent is used. Observe carefully.

Question: Display the processes, which are running under yourusername ?
Answer: - ps –aef | grep MaheshvjHere, Maheshvj is the username.

Question: List some Hot Keys for bash shell ?
Answer: - Ctrl+l – Clears the Screen. Ctrl+r –

Question: Does a search in previously given commands in shell. Ctrl+u - Clears the typing before the hotkey. Ctrl+a – Places cursor at the beginning of the command at shell. Ctrl+e – Places cursor at the end of the command at shell. Ctrl+d – Kills the shell. Ctrl+z – Places the currently running process into background.

Question: Display the files in the directory by file size ?
Answer: - ls –ltr | sort –nr –k 5
How to save man pages to a file ? - man | col –b > Example : man top | col –b > top_help.txt

Question: How to know the date & time for – when script is executed ?
Answer: - Add the following script line in shell script.eval echo "Script is executed at `date`" >> timeinfo.infHere, “timeinfo.inf” contains date & time details ie., when script is executed and history related to execution.

Question: How do you find out drive statistics ?
Answer: - iostat -E

Question: Display disk usage in Kilobytes ?
Answer: - du -k

Question: Display top ten largest files/directories ?
Answer: - du -sk * | sort -nr | head

Question: How much space is used for users in kilobytes ?
Answer: - quot -af

Question: How to create null file ? - cat /dev/null > filename1
Access common commands quicker ? - ps -ef | grep -i $@

Question: Display the page size of memory ?
Answer: - pagesize -a

Question: Display Ethernet Address arp table ?
Answer: - arp -a

Question: Display the no.of active established connections to localhost ? - netstat -a | grep EST
Question: Display the state of interfaces used for TCP/IP traffice ?
Answer: - netstat -i

Question: Display the parent/child tree of a process ?
Answer: - ptree Example: ptree 1267

Question: Show the working directory of a process ?
Answer: - pwdx Example: pwdx 1267

Question: Display the processes current open files ?
Answer: - pfiles Example: pfiles 1267

Question: Display the inter-process communication facility status ?
Answer: - ipcs

Question: Display the top most process utilizing most CPU ?
Answer: - top –b 1

Question:Alternative for top command ?
Answer: - prstat –a

Friday, April 3, 2009

ASP.NET Serialization

1. What is serialization?

Ans. Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

2. Does the .NET Framework have in-built support for serialization?

Ans. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

3. I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?

Ans. It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents.
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

4 Can I customise the serialization process?

Ans. Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

5. Why is XmlSerializer so slow?

Ans. There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

6. Why do I get errors when I try to serialize a Hashtable?

Ans. XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

7. XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?

Ans. Look at the InnerException property of the exception that is thrown to get a more specific error message.

ASP.NET Garbage Collection

1 What is garbage collection?

Ans. Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

2. Is it true that objects don't always get destroyed immediately when the last reference goes away?

Ans. Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed.
There is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#:
In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem:
Chris Sells' response to Brian's posting is here:

3. Why doesn't the .NET runtime offer deterministic destruction?

Ans. Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap.
Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

4. Is the lack of deterministic destruction in .NET a problem?

Ans. It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

5. Does non-deterministic destruction affect the usage of COM objects from managed code?

Ans. Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

6. I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?

Ans. An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources.
Microsoft recommend the following pattern:
public class CTest : IDisposable
public void Dispose()
... // Cleanup activities

~CTest() // C# syntax hiding the Finalize() method
In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

7. Do I have any control over the garbage collection algorithm?

Ans. A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately.
5.8 How can I find out what the garbage collector is doing?
Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters. Use Performance Monitor to view them.

.NET Assemblies

1. What is an assembly?

Ans. An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.

2. How can I produce an assembly?

Ans. The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
public CTest()
System.Console.WriteLine( "Hello from CTest" );
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

3. What is the difference between a private assembly and a shared assembly?

Ans. Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

· Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

4. How do assemblies find each other?

Ans. By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

5. How does assembly versioning work?

Ans. Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.
The version number has four numeric parts (e.g. Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.
Remember: versioning is only applied to shared assemblies, not private assemblies.

.NET Assemblies

1. What is an assembly?

Ans. An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.

2. How can I produce an assembly?

Ans. The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
public CTest()
System.Console.WriteLine( "Hello from CTest" );
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

3. What is the difference between a private assembly and a shared assembly?

Ans. · Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

· Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.
3.4 How do assemblies find each other?
By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.
3.5 How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.
The version number has four numeric parts (e.g. Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.
Remember: versioning is only applied to shared assemblies, not private assemblies.

.NET Basic terminology

1 What is the CLR?

Ans. CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
· Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)
· Security model
· Type system
· All .NET base classes
· Many .NET framework classes
· Development, debugging, and profiling tools
· Execution and code management
· IL-to-native translators and optimizers
What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

2. What is the CTS?

Ans. CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

3. What is the CLS?

Ans. CLS = Common Language Specification. This is a subset of the CTS which all .NET languages are expected to support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

4. What is IL?

Ans. IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

5. What is C#?

Ans. C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#" whitepaper, Microsoft describe C# as follows:
"C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."
Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-).

6. What does 'managed' mean in the .NET context?

Ans. The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly different things.
Managed code: The .NET framework provides several core run-time services to the programs that run within it - for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.
Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

7. What is reflection?

Ans. All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

What is .NET

1. What is .NET?

Ans. That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways".
A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.
Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

2. Does .NET only apply to people building web-sites?

Ans. No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you - not least ASP.NET.

3. When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

4. When was the first version of .NET released?

Ans. The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers.

5. What tools can I use to develop .NET applications?

Ans. There are a number of tools, described here in ascending order of cost:
· .NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.
· ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.
· Microsoft Visual C# .NET Standard 2003: This is a cheap (around $100) version of Visual Studio limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.
· Microsoft Visual Studio.NET Professional 2003: If you have a license for Visual Studio 6.0, you can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.
At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at

6. What platforms does the .NET Framework run on?

Ans. The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home.
The Mono project is attempting to implement the .NET framework on Linux.

7. What languages does the .NET Framework support?

Ans. MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop .NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

8. Will the .NET Framework go through a standardisation process?

Ans. From "On December 13, 2001, the ECMA General Assembly ratified the C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)."

XML interview Questions Part II

1. How to configure the sites in Web server (IIS)?

2. Advantages in IIS 6.0?

3. IIS Isolation Levels?

Ans. Internet Information Server introduced the notion "Isolation Level", which is also present in IIS4 under a different name. IIS5 supports three isolation levels, that you can set from the Home Directory tab of the site's Properties dialog:
· Low (IIS Process): ASP pages run in INetInfo.Exe, the main IIS process, therefore they are executed in-process. This is the fastest setting, and is the default under IIS4. The problem is that if ASP crashes, IIS crashes as well and must be restarted (IIS5 has a reliable restart feature that automatically restarts a server when a fatal error occurs).
· Medium (Pooled): In this case ASP runs in a different process, which makes this setting more reliable: if ASP crashes IIS won't. All the ASP applications at the Medium isolation level share the same process, so you can have a web site running with just two processes (IIS and ASP process). IIS5 is the first Internet Information Server version that supports this setting, which is also the default setting when you create an IIS5 application. Note that an ASP application that runs at this level is run under COM+, so it's hosted in DLLHOST.EXE (and you can see this executable in the Task Manager).
· High (Isolated): Each ASP application runs out-process in its own process space, therefore if an ASP application crashes, neither IIS nor any other ASP application will be affected. The downside is that you consume more memory and resources if the server hosts many ASP applications. Both IIS4 and IIS5 supports this setting: under IIS4 this process runs inside MTS.EXE, while under IIS5 it runs inside DLLHOST.EXE.
When selecting an isolation level for your ASP application, keep in mind that out-process settings - that is, Medium and High - are less efficient than in-process (Low). However, out-process communication has been vastly improved under IIS5, and in fact IIS5's Medium isolation level often deliver better results than IIS4's Low isolation. In practice, you shouldn't set the Low isolation level for an IIS5 application unless you really need to serve hundreds pages per second.

XML Interview Questions Part I

1. Explain what a DiffGram is, and a good use for one?

Ans. A DiffGram is an XML format that is used to identify current and original versions of data elements. When sending and retrieving a DataSet from an XML Web service, the DiffGram format is implicitly used.
The DataSet uses the DiffGram format to load and persist its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.
DiffGram Format
The DiffGram format is divided into three sections: the current data, the original (or "before") data, and an errors section, as shown in the following example.


The DiffGram format consists of the following blocks of data:

The name of this element, DataInstance, is used for explanation purposes in this documentation. A DataInstance element represents a DataSet or a row of a DataTable. Instead of DataInstance, the element would contain the name of the DataSet or DataTable. This block of the DiffGram format contains the current data, whether it has been modified or not. An element, or row, that has been modified is identified with the diffgr:hasChanges annotation.

This block of the DiffGram format contains the original version of a row. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

This block of the DiffGram format contains error information for a particular row in the DataInstance block. Elements in this block are matched to elements in the DataInstance block using the diffgr:id annotation.

2. If I replace my Sqlserver with XML files and how about handling the same?

3. Write syntax to serialize class using XML Serializer?


4. In which process does IIS runs (was asking about the EXE file)

inetinfo.exe is the Microsoft 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 to the actual worker process

5. Where are the IIS log files stored?

Ans. C:\WINDOWS\system32\Logfiles\W3SVC1

6. What are the different IIS authentication modes in IIS 5.0 and Explain? Difference between basic and digest authentication modes?

Ans. IIS provides a variety of authentication schemes:
· Anonymous (enabled by default)
· Basic
· Digest
· Integrated Windows authentication (enabled by default)
· Client Certificate Mapping
Anonymous authentication gives users access to the public areas of your Web site without prompting them for a user name or password. Although listed as an authentication scheme, it is not technically performing any client authentication because the client is not required to supply any credentials. Instead, IIS provides stored credentials to Windows using a special user account, IUSR_machinename. By default, IIS controls the password for this account. Whether or not IIS controls the password affects the permissions the anonymous user has. When IIS controls the password, a sub authentication DLL (iissuba.dll) authenticates the user using a network logon. The function of this DLL is to validate the password supplied by IIS and to inform Windows that the password is valid, thereby authenticating the client. However, it does not actually provide a password to Windows. When IIS does not control the password, IIS calls the LogonUser() API in Windows and provides the account name, password and domain name to log on the user using a local logon. After the logon, IIS caches the security token and impersonates the account. A local logon makes it possible for the anonymous user to access network resources, whereas a network logon does not.
Basic Authentication
IIS Basic authentication as an implementation of the basic authentication scheme found in section 11 of the HTTP 1.0 specification.
As the specification makes clear, this method is, in and of itself, non-secure. The reason is that Basic authentication assumes a trusted connection between client and server. Thus, the username and password are transmitted in clear text. More specifically, they are transmitted using Base64 encoding, which is trivially easy to decode. This makes Basic authentication the wrong choice to use over a public network on its own.
Basic Authentication is a long-standing standard supported by nearly all browsers. It also imposes no special requirements on the server side -- users can authenticate against any NT domain, or even against accounts on the local machine. With SSL to shelter the security credentials while they are in transmission, you have an authentication solution that is both highly secure and quite flexible.
Digest Authentication
The Digest authentication option was added in Windows 2000 and IIS 5.0. Like Basic authentication, this is an implementation of a technique suggested by Web standards, namely RFC 2069 (superceded by RFC 2617).
Digest authentication also uses a challenge/response model, but it is much more secure than Basic authentication (when used without SSL). It achieves this greater security not by encrypting the secret (the password) before sending it, but rather by following a different design pattern -- one that does not require the client to transmit the password over the wire at all.
Instead of sending the password itself, the client transmits a one-way message digest (a checksum) of the user's password, using (by default) the MD5 algorithm. The server then fetches the password for that user from a Windows 2000 Domain Controller, reruns the checksum algorithm on it, and compares the two digests. If they match, the server knows that the client knows the correct password, even though the password itself was never sent. (If you have ever wondered what the default ISAPI filter "md5filt" that is installed with IIS 5.0 is used for, now you know.
Integrated Windows Authentication
Integrated Windows authentication (formerly known as NTLM authentication and Windows NT Challenge/Response authentication) can use either NTLM or Kerberos V5 authentication and only works with Internet Explorer 2.0 and later.
When Internet Explorer attempts to access a protected resource, IIS sends two WWW-Authenticate headers, Negotiate and NTLM.
· If Internet Explorer recognizes the Negotiate header, it will choose it because it is listed first. When using Negotiate, the browser will return information for both NTLM and Kerberos. At the server, IIS will use Kerberos if both the client (Internet Explorer 5.0 and later) and server (IIS 5.0 and later) are running Windows 2000 and later, and both are members of the same domain or trusted domains. Otherwise, the server will default to using NTLM.
· If Internet Explorer does not understand Negotiate, it will use NTLM.
So, which mechanism is used depends upon a negotiation between Internet Explorer and IIS.
When used in conjunction with Kerberos v5 authentication, IIS can delegate security credentials among computers running Windows 2000 and later that are trusted and configured for delegation. Delegation enables remote access of resources on behalf of the delegated user.
Integrated Windows authentication is the best authentication scheme in an intranet environment where users have Windows domain accounts, especially when using Kerberos. Integrated Windows authentication, like digest authentication, does not pass the user's password across the network. Instead, a hashed value is exchanged.
Client Certificate Mapping
A certificate is a digitally signed statement that contains information about an entity and the entity's public key, thus binding these two pieces of information together. A trusted organization (or entity) called a Certification Authority (CA) issues a certificate after the CA verifies that the entity is who it says it is. Certificates can contain different types of data. For example, an X.509 certificate includes the format of the certificate, the serial number of the certificate, the algorithm used to sign the certificate, the name of the CA that issued the certificate, the name and public key of the entity requesting the certificate, and the CA's signature. X.509 client certificates simplify authentication for larger user bases because they do not rely on a centralized account database. You can verify a certificate simply by examining the certificate.

7. Explain the concept of data island?
8. How to use XML DOM model on client side using JavaScript.
9. What are the ways to create a tree view control using XML, XSL & JavaScript?
10. Questions on XPathNavigator, and the other classes in System.XML Namespace?
11. What is Use of Template in XSL?
12. What is “Well Formed XML” and “Valid XML”
13. How you will do SubString in XSL
14. Can we do sorting in XSL ? how do you deal sorting columns dynamically in XML.
15. What is “Async” property of XML Means ?
16. What is XPath Query ?
17. Difference Between Element and Node.
18. What is CDATA Section.
19. DOM & SAX parsers explanation and difference
20. What is GetElementbyname method will do?
21. What is selectnode method will give?
22. What is valid xml document? What a well formed xml document?
23. What is the Difference between XmlDocument and XmlDataDocument?

ASP.NET Web Service and Remoting Interview Questions Part II

16. What is Remoting?

Ans. The process of communication between different operating system processes, regardless of whether they are on the same computer. The .NET remoting system is an architecture designed to simplify communication between objects living in different application domains, whether on the same computer or not, and between different contexts, whether in the same application domain or not.

17. Difference between web services & remoting?

Ans. ASP.NET Web Services .NET Remoting
Protocol Can be accessed only over HTTP Can be accessed over any protocol (including TCP, HTTP, SMTP and so on)
State Management Web services work in a stateless environment Provide support for both stateful and stateless environments through Singleton and SingleCall objects
Type System Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized. Using binary communication, .NET Remoting can provide support for rich type system
Interoperability Web services support interoperability across platforms, and are ideal for heterogeneous environments. .NET remoting requires the client be built using .NET, enforcing homogenous environment.
Reliability Highly reliable due to the fact that Web services are always hosted in IIS Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application.
Extensibility Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Very extensible by allowing us to customize the different components of the .NET remoting framework.
Ease-of-Programming Easy-to-create and deploy. Complex to program.

18. Though both the .NET Remoting infrastructure and ASP.NET Web services can enable cross-process communication, each is designed to benefit a different target audience. ASP.NET Web services provide a simple programming model and a wide reach. .NET Remoting provides a more complex programming model and has a much narrower reach.
As explained before, the clear performance advantage provided by TCPChannel-remoting should make you think about using this channel whenever you can afford to do so. If you can create direct TCP connections from your clients to your server and if you need to support only the .NET platform, you should go for this channel. If you are going to go cross-platform or you have the requirement of supporting SOAP via HTTP, you should definitely go for ASP.NET Web services.
Both the .NET remoting and ASP.NET Web services are powerful technologies that provide a suitable framework for developing distributed applications. It is important to understand how both technologies work and then choose the one that is right for your application. For applications that require interoperability and must function over public networks, Web services are probably the best bet. For those that require communications with other .NET components and where performance is a key priority, .NET Remoting is the best choice. In short, use Web services when you need to send and receive data from different computing platforms, use .NET Remoting when sending and receiving data between .NET applications. In some architectural scenarios, you might also be able to use.NET Remoting in conjunction with ASP.NET Web services and take advantage of the best of both worlds.
The Key difference between ASP.NET webservices and .NET Remoting is how they serialize data into messages and the format they choose for metadata. ASP.NET uses XML serializer for serializing or Marshalling. And XSD is used for Metadata. .NET Remoting relies on System.Runtime.Serialization.Formatter.Binary and System.Runtime.Serialization.SOAPFormatter and relies on .NET CLR Runtime assemblies for metadata.

19. Can you pass SOAP messages through remoting?

20. CAO and SAO.

Ans. Client Activated objects are those remote objects whose Lifetime is directly Controlled by the client. This is in direct contrast to SAO. Where the server, not the client has complete control over the lifetime of the objects.
Client activated objects are instantiated on the server as soon as the client request the object to be created. Unlike as SAO a CAO doesn’t delay the object creation until the first method is called on the object. (In SAO the object is instantiated when the client calls the method on the object)

21. singleton and singlecall.

Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance.
Single Call types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system.

22. What is Asynchronous Web Services?

23. Web Client class and its methods?

24. Flow of remoting?

25. What is the use of trace utility?

Ans. Using the SOAP Trace Utility
The Microsoft® Simple Object Access Protocol (SOAP) Toolkit 2.0 includes a TCP/IP trace utility, MSSOAPT.EXE. You use this trace utility to view the SOAP messages sent by HTTP between a SOAP client and a service on the server.
Using the Trace Utility on the Server
To see all of a service's messages received from and sent to all clients, perform the following steps on the server.
1. On the server, open the Web Services Description Language (WSDL) file.
2. In the WSDL file, locate the element that corresponds to the service and change the location attribute for this element to port 8080. For example, if the location attribute specifies
change this attribute to .
3. Run MSSOAPT.exe.
4. On the File menu, point to New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
5. In the Trace Setup dialog box, click OK to accept the default values.
Using the Trace Utility on the Client
To see all messages sent to and received from a service, do the following steps on the client.
6. Copy the WSDL file from the server to the client.
7. Modify location attribute of the element in the local copy of the WSDL document to direct the client to localhost:8080 and make a note of the current host and port. For example, if the WSDL contains , change it to and make note of "MyServer".
8. On the client, run MSSOPT.exe.
9. On the File menu, point to New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
10. In the Destination host box, enter the host specified in Step 2.
11. In the Destination port box, enter the port specified in Step 2.
12. Click OK.

ASP.NET Web Service and Remoting Interview Questions Part I

1. What is a WebService and what is the underlying protocol used in it?Why Web Services?

Ans. 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.
There are three main uses of Web services.
1. Application integration Web services within an intranet are commonly used to integrate business applications running on disparate platforms. For example, a .NET client running on Windows 2000 can easily invoke a Java Web service running on a mainframe or Unix machine to retrieve data from a legacy application.
2. Business integration Web services allow trading partners to engage in e-business leveraging the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code.
3. Commercial Web services focus on selling content and business services to clients over the Internet similar to familiar Web pages. Unlike Web pages, commercial Web services target applications not humans as their direct users. Continental Airlines exposes flight schedules and status Web services for travel Web sites and agencies to use in their applications. Like Web pages, commercial Web services are valuable only if they expose a valuable service or content. It would be very difficult to get customers to pay you for using a Web service that creates business charts with the customers? data. Customers would rather buy a charting component (e.g. COM or .NET component) and install it on the same machine as their application. On the other hand, it makes sense to sell real-time weather information or stock quotes as a Web service. Technology can help you add value to your services and explore new markets, but ultimately customers pay for contents and/or business services, not for technology

2. Are Web Services a replacement for other distributed computing platforms?

Ans. No. Web Services is just a new way of looking at existing implementation platforms.

3. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?

Ans. A: WebService will support only DataSet.

4. How to generate WebService proxy? What is SOAP, WSDL, UDDI and the concept behind Web Services? What are various components of WSDL? What is the use of WSDL.exe utility?

Ans. SOAP is an XML-based messaging framework specifically designed for exchanging formatted data across the Internet, for example using request and reply messages or sending entire documents. SOAP is simple, easy to use, and completely neutral with respect to operating system, programming language, or distributed computing platform.
After SOAP became available as a mechanism for exchanging XML messages among enterprises (or among disparate applications within the same enterprise), a better way was needed to describe the messages and how they are exchanged. The Web Services Description Language (WSDL) is a particular form of an XML Schema, developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current WSDL spec describes how to map messages and operations to SOAP 1.1, HTTP GET/POST, and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols (using "ports").
The Universal Description, Discovery, and Integration (UDDI) framework defines a data model (in XML) and SOAP APIs for registration and searches on business information, including the web services a business exposes to the Internet. UDDI is an independent consortium of vendors, founded by Microsoft, IBM, and Ariba, for the purpose of developing an Internet standard for web service description registration and discovery. Microsoft, IBM, and Ariba also are hosting the initial deployment of a UDDI service, which is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses). UDDI uses a private agreement profile of SOAP (i.e. UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use the SOAP APIs to register themselves with UDDI, and other businesses search UDDI when they want to discover a trading partner, for example someone from whom they wish to procure sheet metal, bolts, or transistors. The information in UDDI is categorized according to industry type and geographical location, allowing UDDI consumers to search through lists of potentially matching businesses to find the specific one they want to contact. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes.

5. How to generate proxy class other than .net app and wsdl tool?

Ans. To access an XML Web service from a client application, you first add a Web reference, which is a reference to an XML Web service. When you create a Web reference, Visual Studio creates an XML Web service proxy class automatically and adds it to your project. This proxy class exposes the methods of the XML Web service and handles the marshalling of appropriate arguments back and forth between the XML Web service and your application. Visual Studio uses the Web Services Description Language (WSDL) to create the proxy.
To generate an XML Web service proxy class:
· From a command prompt, use Wsdl.exe to create a proxy class, specifying (at a minimum) the URL to an XML Web service or a service description, or the path to a saved service description.
Wsdl /language:language /protocol:protocol /namespace:myNameSpace /out:filename
/username:username /password:password /domain:domain

6. What is a proxy in web service? How do I use a proxy server when invoking a Web service?

7. asynchronous web service means?

8. What are the events fired when web service called?

9. How will do transaction in Web Services?

10. How does SOAP transport happen and what is the role of HTTP in it? How you can access a webservice using soap?

11. What are the different formatters can be used in both? Why?.. binary/soap

12. How you will protect / secure a web service?

Ans. For the most part, things that you do to secure a Web site can be used to secure a Web Service. If you need to encrypt the data exchange, you use Secure Sockets Layer (SSL) or a Virtual Private Network to keep the bits secure. For authentication, use HTTP Basic or Digest authentication with Microsoft® Windows® integration to figure out who the caller is.
these items cannot:
· Parse a SOAP request for valid values
· Authenticate access at the Web Method level (they can authenticate at the Web Service level)
· Stop reading a request as soon as it is recognized as invalid

13. How will you expose/publish a webservice?

14. What is disco file?

15. What’s the attribute for webservice method? What is the namespace for creating webservice?



using System.Web;
using System.Web.Services;

ASP.NET Application and Security Interview Questions Part II

11. How can u handle Exceptions in Asp.Net?

12. How can u handle Un Managed Code Exceptions in ASP.Net?

13. - How to find last error which occurred?

Ans. A: Server.GetLastError();
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);

14. How to do Caching in ASP?

Ans. A: <%@ OutputCache Duration="60" VaryByParam="None" %>

VaryByParam value Description
none One version of page cached (only raw GET)
* n versions of page cached based on query string and/or POST body
v1 n versions of page cached based on value of v1 variable in query string or POST body
v1;v2 n versions of page cached based on value of v1 and v2 variables in query string or POST body

15. <%@ OutputCache Duration="60" VaryByParam="none" %>
<%@ OutputCache Duration="60" VaryByParam="*" %>
<%@ OutputCache Duration="60" VaryByParam="name;age" %>
The OutputCache directive supports several other cache varying options
· VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.)
· VaryByControl - for user controls, maintain separate cache entry for properties of a user control
· VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplicationderived class

16. What is the Global ASA(X) File?

17. Any alternative to avoid name collisions other then Namespaces.

Ans. A scenario that two namespaces named N1 and N2 are there both having the same class say A. now in another class i ve written
using N1;using N2;
and i am instantiating class A in this class. Then how will u avoid name collisions?
Ans: using alias
Eg: using MyAlias = MyCompany.Proj.Nested;

18. Which is the namespace used to write error message in event Log File?

19. What are the page level transaction and class level transaction?

20. What are different transaction options?

21. What is the namespace for encryption?

22. What is the difference between application and cache variables?

23. What is the difference between control and component?

24. You ve defined one page_load event in aspx page and same page_load event in code behind how will prog run?

25. Where would you use an IHttpModule, and what are the limitations of any approach you might take in implementing one?

26. Can you edit data in the Repeater control? Which template must you provide, in order to display data in a Repeater control? How can you provide an alternating color scheme in a Repeater control? What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control?

27. What is the use of web.config? Difference between machine.config and Web.config?

Ans. ASP.NET configuration files are XML-based text files--each named web.config--that can appear in any directory on an ASP.NET
Web application server. Each web.config file applies configuration settings to the directory it is located in and to all
virtual child directories beneath it. Settings in child directories can optionally override or modify settings specified in
parent directories. The root configuration file--WinNT\Microsoft.NET\Framework\\config\machine.config--provides
default configuration settings for the entire machine. ASP.NET configures IIS to prevent direct browser access to web.config
files to ensure that their values cannot become public (attempts to access them will cause ASP.NET to return 403: Access
At run time ASP.NET uses these web.config configuration files to hierarchically compute a unique collection of settings for
each incoming URL target request (these settings are calculated only once and then cached across subsequent requests; ASP.NET
automatically watches for file changes and will invalidate the cache if any of the configuration files change).

28. What is the use of sessionstate tag in the web.config file?

Ans. Configuring session state: Session state features can be configured via the section in a web.config file. To double the default timeout of 20 minutes, you can add the following to the web.config file of an application:
29. What are the different modes for the sessionstates in the web.config file?

Ans. Off Indicates that session state is not enabled.
Inproc Indicates that session state is stored locally.
StateServer Indicates that session state is stored on a remote server.
SQLServer Indicates that session state is stored on the SQL Server.

30. What is smart navigation?

Ans. When a page is requested by an Internet Explorer 5 browser, or later, smart navigation enhances the user's experience of the page by performing the following:
· eliminating the flash caused by navigation.
· persisting the scroll position when moving from page to page.
· persisting element focus between navigations.
· retaining only the last page state in the browser's history.
Smart navigation is best used with ASP.NET pages that require frequent postbacks but with visual content that does not change dramatically on return. Consider this carefully when deciding whether to set this property to true.
Set the SmartNavigation attribute to true in the @ Page directive in the .aspx file. When the page is requested, the dynamically generated class sets this property.

31. In what order do the events of an ASPX page execute. As a developer is it important to undertsand these events?

32. How would you get ASP.NET running in Apache web servers - why would you even do this?

33. What tags do you need to add within the asp:datagrid tags to bind columns manually

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

Ans. System.Web.UI.Page

35. How can we create pie chart in

36. Is it possible for me to change my aspx file extension to some other name?

Ans. Yes.
Open IIS->Default Website -> Properties
Select HomeDirectory tab
Click on configuration button
Click on add. Enter aspnet_isapi details (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG)

Open machine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG) & add new extension under tag

37. What is AutoEventWireup attribute for ?

ASP.NET Application and Security Interview Questions Part I

1. Security types in ASP/ASP.NET? Different Authentication modes?

2. How .Net has implemented security for web applications?

3. How to do Forms authentication in

4. Explain authentication levels in .net ?

5. Explain autherization levels in .net ?

6. What is Role-Based security?

Ans. A role is a named set of principals that have the same privileges with respect to security (such as a teller or a manager). A principal can be a member of one or more roles. Therefore, applications can use role membership to determine whether a principal is authorized to perform a requested action.

7. How will you do windows authentication and what is the namespace?

Ans. If a user is logged under integrated windows authentication mode, but he is still not able to logon, what might be the possible cause for this? In ASP.Net application how do you find the name of the logged in person under windows authentication?

8. What are the different authentication modes in the .NET environment?

timeout="30" path="/" >

Attribute Option Description
mode Controls the default authentication mode for an application.
Windows Specifies Windows authentication as the default authentication mode. Use this mode when using any form of Microsoft Internet Information Services (IIS) authentication: Basic, Digest, Integrated Windows authentication (NTLM/Kerberos), or certificates.
Forms Specifies ASP.NET forms-based authentication as the default authentication mode.
Passport Specifies Microsoft Passport authentication as the default authentication mode.
None Specifies no authentication. Only anonymous users are expected or applications can handle events to provide their own authentication.

9. How do you specify whether your data should be passed as Query string and Forms (Mainly about POST and GET)

Ans. Through attribute tag of form tag.

10. What is the other method, other than GET and POST, in ASP.NET?

11. What are validator?

Ans. Name the Validation controls in How do u disable them? Will the validators run in server side or client side? How do you do Client-side validation in .Net? How to disable validator control by client side JavaScript?
A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation ("EnableClientScript" property set to true/false) using client script.
The following validation controls are available in
RequiredFieldValidator Control, CompareValidator Control, RangeValidator Control, RegularExpressionValidator Control, CustomValidator Control, ValidationSummary Control.

12. Which two properties are there on every validation control?

Ans. ControlToValidate, ErrorMessage

13. How do you use css in

Ans. Within the head section of an HTML document that will use these styles, add a link to this external CSS style sheet that
follows this form:

15. How do you implement postback with a text box? What is postback and usestate?

Ans. Make AutoPostBack property to true

16. How can you debug an ASP page, without touching the code?

17. What is SQL injection?

Ans. An SQL injection attack "injects" or manipulates SQL code by adding unexpected SQL to a query.
Many web pages take parameters from web user, and make SQL query to the database. Take for instance when a user login, web page that user name and password and make SQL query to the database to check if a user has valid name and password.
Username: ' or 1=1 ---
Password: [Empty]
This would execute the following query against the users table:
select count(*) from users where userName='' or 1=1 --' and userPass=''

Asp.Net Session State Interview Questions

1. Application and Session Events

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

2. Difference between ASP Session and ASP.NET Session?

Ans. session supports cookie less session & it can span across multiple servers.

3. What is cookie less session? How it works?

Ans. 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:

4. 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?

Ans. 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):

Note that if you try the sample above with this setting, you can reset the Web server (enter iisreset on the command line) and the session state value will persist.

5. What method do you use to explicitly kill a users session?

Ans. Abandon()

6. What are the different ways you would consider sending data across pages in ASP (i.e between 1.asp to 2.asp)?

Ans. Session public properties

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

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

8. What are the disadvantages of view state / what are the benefits?

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

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

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

10. What are the contents of cookie?

11. How do you create a permanent cookie?

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

13. Explain the differences between Server-side and Client-side code?

Ans. Server side code will process at server side & it will send the result to client. Client side code (javascript) will execute only at client side.

14. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?

15. Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform?

A: Many of the ASP.NET configuration options are not configurable at the site, application or subdirectory level on the shared hosting platform. Certain options can affect the security, performance and stability of the server and, therefore cannot be changed. The following settings are the only ones that can be changed in your site’s web.config file (s):

16. Briefly describe the role of global.asax?

17. How can u debug your .net application?

18. How do u deploy your application?

19. Where do we store our connection string in application?

20. Various steps taken to optimize a web based application (caching, stored procedure etc.)

21. How does ASP.NET framework maps client side events to Server side events.

Thursday, April 2, 2009

ADO.NET Interview Questions

1. Advantage of ADO.Net?

· ADO.NET Does Not Depend On Continuously Live Connections
· Database Interactions Are Performed Using Data Commands
· Data Can Be Cached in Datasets
· Datasets Are Independent of Data Sources
· Data Is Persisted as XML
· Schemas Define Data Structures

2. How would u connect to database using .NET?

Ans. SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" +
"Initial Catalog=northwind");

3. What are relation objects in dataset and how & where to use them?

Ans. In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table.
The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.


private void CreateRelation()
// Get the DataColumn objects from two DataTable objects in a DataSet.
DataColumn parentCol;
DataColumn childCol;
// Code to get the DataSet not shown here.
parentCol = DataSet1.Tables["Customers"].Columns["CustID"];
childCol = DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation.
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
// Add the relation to the DataSet.

4. Difference between OLEDB Provider and SqlClient ?

Ans: SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. The SqlClient data provider is fast. It's faster than the Oracle provider, and faster than accessing database via the OleDb layer. It's faster because it accesses the native library (which automatically gives you better performance), and it was written with lots of help from the SQL Server team.

5. What are the different namespaces used in the project to connect the database? What data providers available in .net to connect to database?

· System.Data.OleDb – classes that make up the .NET Framework Data Provider for OLE DB-compatible data sources. These classes allow you to connect to an OLE DB data source, execute commands against the source, and read the results.
· System.Data.SqlClient – classes that make up the .NET Framework Data Provider for SQL Server, which allows you to connect to SQL Server 7.0, execute commands, and read results. The System.Data.SqlClient namespace is similar to the System.Data.OleDb namespace, but is optimized for access to SQL Server 7.0 and later.
· System.Data.Odbc - classes that make up the .NET Framework Data Provider for ODBC. These classes allow you to access ODBC data source in the managed space.
· System.Data.OracleClient - classes that make up the .NET Framework Data Provider for Oracle. These classes allow you to access an Oracle data source in the managed space.

6. Difference between DataReader and DataAdapter / DataSet and DataAdapter?

Ans. You can use the ADO.NET DataReader to retrieve a read-only, forward-only stream of data from a database. Using the DataReader can increase application performance and reduce system overhead because only one row at a time is ever in memory.
After creating an instance of the Command object, you create a DataReader by calling Command.ExecuteReader to retrieve rows from a data source, as shown in the following example.
SqlDataReader myReader = myCommand.ExecuteReader();
You use the Read method of the DataReader object to obtain a row from the results of the query.
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

7. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

Ans. Fill()

8. Explain different methods and Properties of DataReader which you have used in your project?

Ans. Read
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));

9. What happens when we issue Dataset.ReadXml command?

Ans. Reads XML schema and data into the DataSet.

10. In how many ways we can retrieve table records count? How to find the count of records in a dataset?

Ans. foreach(DataTable thisTable in myDataSet.Tables){
// For each row, print the values of each column.
foreach(DataRow myRow in thisTable.Rows){

11. How to check if a datareader is closed or opened?

Ans. IsClosed()

12. What happens when u try to update data in a dataset in .NET while the record is already deleted in SQL SERVER as backend?


What is concurrency? How will you avoid concurrency when dealing with dataset? (One user deleted one row after that another user through his dataset was trying to update same row. What will happen? How will you avoid the problem?)

13. How do you merge 2 datasets into the third dataset in a simple manner? OR If you are executing these statements in commandObject. "Select * from Table1;Select * from Table2” how you will deal result set?

14. How do you sort a dataset?

15. If a dataset contains 100 rows, how to fetch rows between 5 and 15 only?

16. Differences between dataset.clone and dataset.copy?

Ans. Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data.
Copy - Copies both the structure and data for this DataSet.

17. What is the use of parameter object?

18. How to generate XML from a dataset and vice versa?

19. What is method to get XML and schema from Dataset?

Ans: getXML () and get Schema ()

20. How do u implement locking concept for dataset?

C# Constructor & Destructor Interview Questions

1. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use?

Ans. (Class constructor method is also known as type constructor or type initializer)
Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention.
A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced.

2. What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor?

Ans. A: When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes)
Make a constructor private if:
- You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.
- You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

3. I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private?

Ans. (yes)

4. Overloaded constructor will call default constructor internally?

Ans. (no)

5. What are virtual destructors?

6. Destructor and finalize

Ans. Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors.
In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .Net frameworks Garbage Collector (GC). GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method.
Points to remember:
1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.

7. What is the difference between Finalize and Dispose (Garbage collection)

Ans. Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object.
In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

8. What is close method? How its different from Finalize & Dispose?

9. What is boxing & unboxing?

10. What is check/uncheck?

11. What is the use of base keyword? Tell me a practical example for base keyword’s usage?

12. What are the different .net tools which u used in projects?

...//exception occurred here. What'll happen?
Ans : It will throw exception.

13. What will do to avoid prior case?

//exception occurred here.

14. Will it go to finally block if there is no exception happened?

Ans: Yes. The finally block is useful for cleaning up any resources allocated in the try block. Control is always passed to the finally block regardless of how the try block exits.

15. Is goto statement supported in C#? How about Java?

Ans. Gotos are supported in C#to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.

16. What’s different about switch statements in C#?

Ans. No fall-throughs allowed. Unlike the C++ switch statement, C# does not support an explicit fall through from one case label to another. If you want, you can use goto a switch-case, or goto default.
case 1:
cost += 25;
case 2:
cost += 25;
goto case 1;