Saturday, January 31, 2009

621 C# job interview questions and answers

C# interview questions
1. .Net Platform, Language
a. .Net platform,
1. What is .NET Framework? Is .NET a runtime service or a development platform? Microsoft .NET is a company-wide initiative. A part of Microsoft.NET is the .NET Frameworks. The .NET framework consists of two parts: the .NET common language runtime and the .NET class library. These two components are packaged together into the .NET Frameworks SDK. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform.
2. What are the new features of Framework 1.1? a) Native Support for Developing Mobile Web Applications , b) Enable Execution of Windows Forms Assemblies Originating from the Internet Assemblies originating from the Internet zone—for example, Microsoft Windows® Forms controls embedded in an Internet-based Web page or Windows Forms assemblies hosted on an Internet Web server and loaded either through the Web browser or programmatically using the System.Reflection.Assembly.LoadFrom() method—now receive sufficient permission to execute in a semi-trusted manner. Default security policy has been changed so that assemblies assigned by the common language runtime (CLR) to the Internet zone code group now receive the constrained permissions associated with the Internet permission set. c) Enable Code Access Security for ASP.NET Applications Systems administrators can now use code access security to further lock down the permissions granted to ASP.NET Web applications and Web services. Although the operating system account under which an application runs imposes security restrictions on the application, the code access security system of the CLR can enforce additional restrictions on selected application resources based on policies specified by systems administrators. You can use this feature in a shared server environment to isolate separate applications from one another, as well as with stand-alone servers where you want applications to run with the minimum necessary privileges. d) Native Support for Communicating with ODBC and Oracle Databases e) Unified Programming Model for Smart Client Application Development
The Microsoft .NET Compact Framework brings the CLR, Windows Forms controls, and other .NET Framework features to small devices. The .NET Compact Framework supports a large subset of the .NET Framework class library optimized for small devices. A) Support for IPv6 The .NET Framework 1.1 supports the emerging update to the Internet Protocol, commonly referred to as IP version 6, or simply IPv6. This protocol is designed to significantly increase the address space used to identify communication endpoints in the Internet to accommodate its ongoing growth.
3. What is CLR? How it will work? The common language runtime (CLR) is the foundation upon which the Microsoft® .NET strategy is built. The CLR provides an execution environment that manages running code and provides services that make software development easier. These services include automatic memory management, cross-language integration, interoperability with existing code and systems, simplified deployment, and a finely grained security system
4. What is CLR, CTS, CLS? The .NET Framework provides a runtime environment called the Common Language Runtime or CLR (similar JVM in Java), which handles the execution of code and provides useful services for the implementation of the program. CLR takes care of code management at program execution and provides various beneficial services such as memory management, thread management, security management, code verification, compilation, and other system services. The managed code that targets CLR benefits from useful features such as cross-language integration, cross-language exception handling, versioning, enhanced security, deployment support, and debugging.  Common Type System (CTS) describes how types are declared, used and managed in the runtime and facilitates cross-language integration, type safety, and high performance code execution. The CLS is simply a specification that defines the rules to support language integration in such a way that programs written in any language, yet can interoperate with one another, taking full advantage of inheritance, polymorphism, exceptions, and other features.
5. What is MSIL, IL, CTS? MSIL is a CPU-independent intermediate language created by Microsoft. MSIL is much higher level than most CPU machine languages. MSIL can be written in assembly language. Microsoft provides an MSIL assembler, ILAsm.exe, as well as an MSIL disassembler, ILDasm.exe. The formal specification of the type system implemented by the common language runtime is called the Common Type System (CTS). The CTS also specifies the rules for type visibility and for access to the members of a type. In addition, the CTS defines the rules governing type inheritance, virtual functions, object lifetime, and so on.
6. What is MSIL, IL? When compiling to managed code, the compiler translates your source code into Microsoft intermediate language (MSIL), which is a CPU-independent set of instructions that can be efficiently converted to native code. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations. Microsoft intermediate language (MSIL) is a language used as the output of a number of compilers and as the input to a just-in-time (JIT) compiler. The common language runtime includes a JIT compiler for converting MSIL to native code.
7. Can I write IL programs directly? Yes. Just simple example to the DOTNET mailing list:^K.assembly MyAssembly {}^K.class MyApp {^K  .method static void Main() {^K    .entrypoint^K    ldstr      "Hello, IL!"^K    call       void System.Console::WriteLine(class System.Object)^K    ret^K  }^K}^KJust put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
8. Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.
9. What is JIT (just in time)? how it works? Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access.
10. Explain JIT activation. The objective of JIT activation is to minimize the amount of time for which an object lives and consumes resources on the server. With JIT activation, the client can hold a reference to an object on the server for a long time, but the server creates the object only when the client calls a method on the object. After the method call is completed, the object is freed and its memory is reclaimed. JIT activation enables applications to scale up as the number of users increases.
11. Without modifying source code if we compile again, will it be generated MSIL again?
12. What is portable executable (PE)? The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.
13. Briefly describe the major components of the .NET Framework and describe what each component does. The .NET Framework consists of two primary parts: the common language runtime, which manages application execution, enforces type safety, and manages memory reclamation, and the .NET base class library, which consists of thousands of predeveloped classes that can be used to build applications.
14. Describe the compilation process for .NET code? Source code is compiled and run in the .NET Framework using a two-stage process. First, source code is compiled to Microsoft intermediate language (MSIL) code using a .NET Framework-compatible compiler, such as that for Visual Basic .NET or Visual C#. Second, MSIL code is compiled to native code.
15. Describe the Managed Execution Process? The managed execution process includes the following steps: a. Choosing a compiler. To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime. b. Compiling your code to Microsoft intermediate language (MSIL).  Compiling translates your source code into MSIL and generates the required metadata. c. Compiling MSIL to native code.  At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe. d. Executing your code.  The common language runtime provides the infrastructure that enables execution to take place as well as a variety of services that can be used during execution.
b. Construction of program, namespaces
16. Can you write a class without specifying namespace? Which namespace does it belong to by default? Yes, you can, then the class belongs to global namespace which has no name. For commercial products, naturally, you wouldn’t want global namespace.
17. What are Namespaces? The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable.
18. Is it namespace class or class namespace? The .NET class library is organized into namespaces. Each namespace contains a functionally related group of classes so natural namespace comes first.
19. What’s different about namespace declaration when comparing that to package declaration in Java? No semicolon. Package declarations also have to be the first thing within the file, can’t be nested, and affect all classes within the file.
20.What are valid signatures for the Main function?
public static void Main()
public static int Main()
public static void Main( string[] args )
public static int Main(string[] args )
21. Does Main() always have to be public? No.
22. What’s the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments.
23. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch.
24. using directive vs using statement The using directive has two uses. 1) Create an alias for a namespace (a using alias). 2) Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (a using directive).
You create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. The using statement defines a scope at the end of which an object will be disposed. A using statement can be exited either when the end of the using statement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement.
public class TestMain{
 static public void Main(){
   using (Test t = new Test() ){
      t.Hello();
   }
}}
25. How do you enable your application to use .NET base class library members without referencing their fully qualified names? Use the using keyword to make a .NET Framework namespace visible to your application.
26. What are main namespaces in .Net class library?
Namespace       Description             System  Contains fundamental classes and base classes that define commonly-used value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions, data type conversion, method parameter manipulation, mathematics, remote and local program invocation, application environment management, and supervision of managed and unmanaged applications.         System.Collections      Contains interfaces and classes that define various collections of objects, such as lists, queues, arrays, hashtables and dictionaries          System.Data     Consists mostly of the classes that constitute the ADO.NET architecture         System.Data.OleDb       OLE DB .NET Data Provider               System.Data.SqlClient   SQL Server .NET Data Provider           System.Data.SqlTypes    provides classes for native data types within SQL Server                System.Diagnostics      Provides classes that allow you to debug your application and to trace the execution of your code.              System.DirectoryServices        Provides easy access to the Active Directory from managed code.                 System.Drawing  Provides access to GDI+ basic graphics functionality            System.Drawing.Printing         Allows you to customize printing                System.EnterpriseServices       Supporting COM+ functionalities, serviced components            System.Globalization    Contains classes that define culture-related information, including the language, the country/region, the calendars in use, the format patterns for dates, currency and numbers, and the sort order for strings.                System.IO       Contains types that allow synchronous and asynchronous reading and writing on data streams and files.           System.Management.Instrumentation       Using to write MMC snap-in for Window services          System.Net      provides a simple programming interface to many of the protocols found on the network today (cookie,…)          System.Net.Sockets      Provides a managed implementation of the Windows Sockets interface for developers that need to tightly control access to the network            System.Reflection       Contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.              System.Resources        Provides classes and interfaces that allow developers to create, store and manage various culture-specific resources used in an application             System.Runtime.InteropServices  Provides a collection of classes useful for accessing COM objects, and native APIs from .NET            System.Runtime.Remoting         Provides classes and interfaces that allow developers to create and configure distributed applications.         System.Runtime.Remoting.Channels        Contains classes that support and handle channels and channel sinks, which are used as the transport medium when a client calls a method on a remote object.            System.Runtime.Serialization    Contains classes that can be used for serializing and deserializing objects.            System.Security         Provides the underlying structure of the common language runtime security system, including base classes for permissions.               System.Security.Permissions     Defines classes that control access to operations and resources based on policy.                System.Security.Principal       Defines a principal object that represents the security context under which code is running.            System.ServiceProcess   Provides classes that allow you to install and run services.            System.Text     Contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String (StringBuffer)              System.Threading        Provides classes and interfaces that enable multi-threaded programming.         System.Web      Supplies classes and interfaces that enable browser/server communication                System.Web.Services     Consists of the classes that enable you to build and use Web Services.          System.Web.UI   Provides classes and interfaces that allow you to create controls and pages that will appear in your Web applications as user interface on a Web page           System.Windows.Forms    Contains classes for creating Windows-based applications that take full advantage of the rich user interface features available in the Microsoft Windows operating system.              System.Xml      Provide standards-based support for processing XML.             c. Assemblies, attributes
27. What is Assembly? Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions: It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main). It forms a security boundary. An assembly is the unit at which permissions are requested and granted. It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly. It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies. It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. It is the unit at which side-by-side execution is supported. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.
28. Types of assemblies? Private, Public/Shared, Satellite
29. What are the different types of assemblies? The different types of assemblies include - Static and dynamic assemblies, Private and shared assemblies, Single-file and multiple-file assemblies
30. What is the difference between a private assembly and a shared assembly? 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.
31. What are Satellite Assemblies? How you will create this? How will you get the different language strings?  Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. (For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.)
32. What are the contents of assembly? In general, a static assembly can consist of four elements: a) The assembly manifest, which contains assembly metadata. b) Type metadata. c) Microsoft intermediate language (MSIL) code that implements the types. d) A set of resources.
33. How will you load dynamic assembly? How will create assemblies at run time?
loader.LoadAssembly(filename);
34. What is Assembly manifest? what all details the assembly manifest will contain. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly’s version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies.
35. What are the contents of assembly? In general, a static assembly can consist of four elements: a) The assembly manifest, which contains assembly metadata. b) Type metadata. c) Microsoft intermediate language (MSIL) code that implements the types. d) A set of resources.
36. Difference between assembly manifest & metadata?  assembly manifest -An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly’s metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. metadata -Information that describes every element managed by the common language runtime: an assembly, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime.
37. If I have more than one version of one assemblies, then how’ll I use old version (how/where to specify version number?)in my application ? [assembly:AssemblyVersion("1.5.*")]
38. What is strong name? A name that consists of an assembly’s identity—its simple text name, version number, and culture information (if provided)—strengthened by a public key and a digital signature generated over the assembly.
39. Describe how to sign your assembly with a strong name. Why would you want to do this? To sign your assembly with a strong name, you must have access to a key file or create one with the strong name utility (sn.exe). You then specify the key file in the AssemblyInfo file and verify that the version number is correct. The assembly will be signed with a strong name when built. In addition to identifying your assembly and ensuring version identity, a strong name is required if you want to install your assembly to the Global Assembly Cache.
40. What is Global Assembly Cache (GAC) and what is the purpose of it? How to make an assembly to public? Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer.  You should share assemblies by installing them into the global assembly cache only when you need to.Steps: a)  Create a strong name using sn.exe tool eg: sn -k keyPair.snk b) - with in AssemblyInfo.cs add the generated file name  eg: [assembly: AssemblyKeyFile("abc.snk")] c) - recompile project, then install it to GAC by either - drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool) or gacutil -i abc.dll
41. How to find methods of a assembly file (not using ILDASM)? Reflection
42. What is Reflection in .NET? Namespace?  How will you load an assembly which is not referenced by current assembly? 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).
43. How many classes can a single .NET DLL contain? Unlimited.
44. How’s the DLL Hell problem solved in .NET? Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
45. What is a native image? How do you create one? A native image is a precompiled version of a .NET assembly. You can create a native image of your application by using the Ngen.exe utility.
46. What is the format of the assembly version stored in the AssemblyInfo file? The assembly version number is a four-part number. The format of the version number is <\major version>.<minor version>.<build number>.<revision>
47. What tasks does the common language runtime perform to locate and bind an assembly? The common language runtime performs the following tasks, in the order listed, to locate and bind to assemblies: a) Determines the correct assembly version, b) Checks for the previously loaded assembly, c) Checks the global assembly cache, d) Locates the assembly through the codebase setting or probing
48. Which attribute do you use to specify the version number of an assembly? You use the AssemblyVersion() attribute to specify the version of an assembly.
49. What is Custom attribute? How to create? If I'm having custom attribute in an assembly, how to say that name in the code? A: The primary steps to properly design custom attribute classes are as follows:
a. Applying the AttributeUsageAttribute
([AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)])
b. Declaring the attribute. (class public class MyAttribute : System.Attribute { // . . . })
c. Declaring constructors (public MyAttribute(bool myvalue) { this.myvalue = myvalue; })
d. Declaring properties
public bool MyProperty {
get {return this.myvalue;}
set {this.myvalue = value;}}
The following example demonstrates the basic way of using reflection to get access to custom attributes. ^Kclass MainClass {
public static void Main(){ System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes();^Kfor (int i = 0; i < attributes.Length; i ++) {System.Console.WriteLine(attributes[i]);}}}
d. general
50. Explain the three services model (three-tier application). Presentation (UI), business (logic and underlying code) and data (from storage or other sources).
51. What are the OOPS concepts? 1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data. 2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors. 3) Polymorphism: It is a feature that allows one interface to be used for general class of actions. The specific action is determined by the exact nature of the situation. In general polymorphism means "one interface, multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation.
52. Explain encapsulation and why it is important in object-oriented programming. Encapsulation is the principle that all of the data and functionality required by an object be contained by that object. This allows objects to exist as independent, interchangeable units of functionality without maintaining dependencies on other units of code.
53. How does C# achieve polymorphism? By using Abstract classes/functions.
54. Can you explain what inheritance is and an example of when you might use it? Inheritance is a fundamental feature of an object oriented system and it is simply the ability to inherit data and functionality from a parent object. Rather than developing new objects from scratch, new code can be based on the work of other programmers, adding only new features that are needed.
55. What is Inheritance, Multiple Inheritance, Shared and Repeatable Inheritance?
**
56. How would you implement inheritance using C#? When we set out to implement a class using inheritance, we must first start with an existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the methods, properties, and events of that base class,  including the implementation behind each method, property, and event. Our subclass can add new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the methods and properties of the base class with its own new implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules for how these methods, properties, and events can be merged.
57. C++ & C# differences
Main() is capitalized
Main() may return void or int
Class declarations do not end with a semi-colon
The keyword new means “obtain a new copy of.” Reference objects are created on the heap but static objects are created on the stack (even with new).
Booleans do not convert to integers
All objects require definite values before being used: definite assignment
All statements that test a Boolean condition require a variable of type bool
You may not fall through a switch statement
Switch statements may switch on string values
Foreach statement iterate over collections
There are no header files
All methods are declared in-line
Structs are value types and sealed
Sealed classes may not act as base classes
Abstract methods are marked with the keyword abstract
Virtual methods must be explicitly overridden
Methods in derived classes may hide virtual methods with the keyword new
There is no multiple inheritance (though you can implement multiple interfaces)
There are no const member functions
There are no const parameters
Const fields are now supported
You may not initialize class members in the class header, but you may initialize members in the body of the class declaration
There are no default parameters for methods
Static methods may not be invoked on instances
There are no global variables or global methods
There is no typedef statement
There are no conversion constructors
There is no destructor (note destructor syntax used for finalize)
There are no forward declarations
e. variables, keywords, operators, data types
58. How big is the datatype int in .NET? 32 bits.
59. How big is the char? 16 bits (Unicode).
60. How do you initiate a string without escaping each backslash? Put an @ sign in front of the double-quoted string.
61. How do you initialize a two-dimensional array that you don’t know the dimensions of?
int [, ] myArray; //declaration
myArray= new int [5, 8]; //actual initialization
62. Can you store multiple data types in System.Array? No.
63. What’s the difference between the System.Array.CopyTo() and System.Array.Clone()? The first one performs a deep copy of the array, the second one is shallow.
64. When a type conversion will undergo an implicit cast and when you must perform an explicit cast. What are the dangers associated with explicit casts? Types can be implicitly converted when the conversion can always take place without any potential loss of data. When a potential loss of data is possible, an explicit cast is required. If an explicit cast is improperly performed, a loss of data precision can result, or an exception can be thrown.
65. What are the similarities and differences between arrays and collections? Arrays and collections allow you to manage groups of objects. You can access a particular object by index in both arrays and collections, and you can use foreach syntax to iterate through the members of arrays and most collections. Arrays are fixed in length, and members must be initialized before use. Members of collections must be declared and initialized outside of the collection, and then added to the collection. Collections provided in the System.Collections namespace can grow or shrink dynamically, and items can be added or removed at run time.
66. What is the difference between Array and LinkedList?
67. What is the difference between Array and Arraylist? As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly.
68. What is Jagged Arrays? A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays."
69. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods.
70. What data type should you use if you want an 8-bit value that’s signed? sbyte.
71. Speaking of Boolean data types, what’s different between C# and C/C++? There’s no conversion between 0 and false, as well as any other number and true, like in C/C++.
72. Where are the value-type variables allocated in the computer RAM? Stack.
73. Where do the reference-type variables go in the RAM? The references go on the stack, while the objects themselves go on the heap. However, in reality things are more elaborate.
74. What is the difference between ref & out parameters? An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter.
75. How do you box a primitive data type variable? Initialize an object with its value, pass an object, cast it to an object
76. Why do you need to box a primitive variable? To pass it by reference or apply a method that an object supports, but primitive doesn’t.
77. What is boxing & unboxing? Boxing and unboxing is a essential concept in C#’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Converting a value type to reference type is called Boxing. Unboxing is an explicit operation. When a variable of a value type needs to be converted to a reference type, an object box is allocated to hold the value, and the value is copied into the box. Unboxing is just the opposite. When an object box is cast back to its original value type, the value is copied out of the box and into the appropriate storage location.
78. How do you convert a string into an integer in .NET? Int32.Parse(string), Convert.ToInt32()
79. Can you create enumerated data types in C#? Yes.
80. What’s different about switch statements in C# as compared to C++?  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.^Kcase 1:^Kcost += 25;^Kbreak;^Kcase 2:^Kcost += 25;^Kgoto case 1;
81. What happens when you encounter a continue statement inside the for loop? The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop.
82. Is goto statement supported in C#? How about Java? Gotos are supported in C# to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality.
83. What’s the .NET datatype that allows the retrieval of data by a unique key? HashTable.
84. What’s class SortedList underneath? A sorted HashTable.
85. Value type & data types difference. A value type holds all of the data represented by the variable within the variable itself. A reference type contains a reference to a memory address that holds the data instead of the actual data itself.
86. Value type & reference types difference? Example from .NET. Integer & struct are value types or reference types in .NET? Most programming languages provide built-in data types, such as integers and floating-point numbers, that are copied when they are passed as arguments (that is, they are passed by value). In the .NET Framework, these are called value types. The runtime supports two kinds of value types: a) Built-in value types - The .NET Framework defines built-in value types, such as System.Int32 and System.Boolean, which correspond and are identical to primitive data types used by programming languages. b) User-defined value types  Your language will provide ways to define your own value types, which derive from System.ValueType. If you want to define a type representing a value that is small, such as a complex number (using two floating-point numbers), you might choose to define it as a value type because you can pass the value type efficiently by value. If the type you are defining would be more efficiently passed by reference, you should define it as a class instead. Variables of reference types, referred to as objects, store references to the actual data. This following are the reference types: class, interface, delegate This following are the built-in reference types: object, string
87. Integer & struct are value types or reference types in .NET? value,
f. classes, interfaces
88. What’s the implicit name of the parameter that gets passed into the class’ set method? Value, and it’s datatype depends on whatever variable we’re changing.
89. Does C# support multiple inheritance? No, use interfaces instead.
90. What’s the top .NET class that everything is derived from? System.Object
91. Which is the base class for .net Class library? system.object
92. What’s an abstract class? A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.
93. When do you absolutely have to declare a class as abstract? When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.
94. What’s an interface class? It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.
95. Can you inherit multiple interfaces? Yes.
96. How can you write a class to restrict that only one object of this class can be created (Singleton class)?

97. And if they have conflicting method names? It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.
98. What’s the difference between an interface and abstract class? In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.
99. In which Scenario you will go for Interface or Abstract Class? Interfaces, like classes, define a set of properties, methods, and events. But unlike classes, interfaces do not provide implementation. They are implemented by classes, and defined as separate entities from classes. Even though class inheritance allows your classes to inherit implementation from a base class, it also forces you to make most of your design decisions when the class is first published. Abstract classes are useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.
100. Describe an abstract class and explain when one might be useful. An abstract class is a class that cannot be instantiated but must be inherited. It can contain both implemented methods and abstract methods, which must be implemented in an inheriting class. Thus, it can define common functionality for some methods, a common interface for other methods, and leave more detailed implementation up to the inheriting class.
101.  What members are, and list the four types of members. Members are the parts of a class or a structure that hold data or implement functionality. The primary member types are fields, properties, methods, and events.
102. What’s the difference between System.String and System.StringBuilder classes? System.String is immutable, System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.
103. What’s the advantage of using System.Text.StringBuilder over System.String? StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.
104. What’s the difference between struct and class in C#? 1) Structs cannot be inherited. 2) Structs are passed by value, not by reference. 3) Struct is stored on the stack, not the heap. The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive. When you create a struct object using the new operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized. It is an error to declare a default (parameterless) constructor for a struct. A default constructor is always provided to initialize the struct members to their default values. It is an error to initialize an instance field in a struct. There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do. A struct is a value type, while a class is a reference type.
105. You need to create several unrelated classes that each exposes a common set of methods. Outline a strategy that will allow these classes to polymorphically expose that functionality to other classes. Factor the common set of methods into an interface, and then implement that interface in each class. Each class can then be implicitly cast to that interface and can polymorphically interact with other classes.
106. You need to create several classes that provide a core set of functionality but each must be able to interact with a different set of objects. Outline a strategy for developing these classes with the least development time. Create a single class that implements all of the common functionality required by these classes. Then, use inheritance to create derived classes that are specific for each individual case.
g. constructors-destructors
107. C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write? Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.
108. Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use? (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.
109. What is Private Constructor? and it’s use? Can you create instance of a class which has Private Constructor? 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: a) - 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. b) - 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.
110. 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? (yes)
111. Overloaded constructor will call default constructor internally? (no)
112. What are virtual destructors? (in C++!)
113. Destructor and finalize 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: a. Destructors are invoked automatically, and cannot be invoked explicitly.^Kb. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.^Kc. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.^Kd. Destructors cannot be used with structs. They are only used with classes.^Ke. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. ^Kf. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.^Kg. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.
h. classes – subclasses , access, methods, properties, overriding
114. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it’s double colon in C++.
115. What constructors and destructors are and what they are used for? The constructor is the method that initializes a class or structure and is run when a type is first instantiated. It is used to set default values and perform other tasks required by the class. A destructor is the method that is run as the object is being reclaimed by garbage collection. It contains any code that is required for cleanup of the object.
116. What are the access-specifiers available in c#? Private, Protected, Public, Internal, Protected Internal.
117. What is the difference between public, internal, and private access levels as they apply to user-defined types and members. In user-defined types, public classes can be instantiated by any element of the application. internal classes can be instantiated only by members of the same assembly, and private classes can be instantiated only by themselves or types they are nested in. Likewise, a public member can be accessed by any client in the application, a internal member can be accessed only from members of the same assembly, and private members can be accessed only from within the type.
118. When you inherit a protected class-level variable, who is it available to? Classes in the same namespace.
119. Are private class-level variables inherited? Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.
120. Describe the accessibility modifier protected internal. It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).
121. Explain about Protected and protected internal, “internal” access-specifier? protected - Access is limited to the containing class or types derived from the containing class. internal - Access is limited to the current assembly. protected internal - Access is limited to the current assembly or types derived from the containing class.
122. How’s method overriding different from overloading? When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.
123. What is method overloading, and when is it useful? Method overloading allows you to create several methods with the same name but different signatures. Overloading is useful when you want to provide the same or similar functionality to different sets of parameters.
124. What does the keyword virtual mean in the method definition? The method can be overridden.
125. Can you declare the override method static while the original method is non-static? No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.
126. How do you call a member of a base class from within a derived class? To refer to a member of a base class use the base keyword.
127. Can you override private virtual methods? No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.
128. What are Sealed Classes in C#? The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class)
129. Can you prevent your class from being inherited and becoming a base class for some other classes? Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.
130. Can you allow class to be inherited, but prevent the method from being over-ridden? Yes, just leave the class public and make the method sealed.
131. Why can’t you specify the accessibility modifier for methods inside the interface? They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, it’s public by default.
132. How can you overload a method? Different parameter data types, different number of parameters, different order of parameters.
133. What is Method Overriding? How to override a function in C#? Use the override modifier to modify a method, a property, an indexer, or an event. An override method provides a new implementation of a member inherited from a base class. The method overridden by an override declaration is known as the overridden base method. The overridden base method must have the same signature as the override method. You cannot override a non-virtual or static method. The overridden base method must be virtual, abstract, or override.
134. In which cases you use override and new base? Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier.
135. If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor? Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.
136. What is the use of base keyword? Tell me a practical example for base keyword’s usage?

137. What’s the access level of the visibility type internal? Current assembly.
138. Do you need to instantiate a class before accessing a static member? Why or why not? Because a static member belongs to the type rather than to any instance of the type, you can access the member without first creating an instance of the type.
139. Can we call a base class method without creating instance? Its possible If its a static method.Its possible by inheriting from that class also. Its possible from derived classes using base keyword.
140. How properties differ from fields? Why would you expose public data through properties instead of fields? Properties allow validation code to execute when values are accessed or changed. This allows you to impose some measure of control over when and how values are read or changed. Fields cannot perform validation when being read or set.
141. How is a property designated as read-only? Only a Get method...no, Set method
142. What’s the difference between const and readonly? You can initialize readonly variables to some runtime values. Let’s say your program uses current date and time as one of the values that won’t change. This way you declare
public readonly string DateT = new DateTime().ToString().
143. Readonly vs. const? A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants.
144. Why you might use enums and constants instead of their associated literal values? Enums and constants make code easier to read and maintain by substituting human-legible tokens for frequently used constant values.
145. What are indexers? Indexers are similar to properties, except that the get and set accessors of indexers take parameters, while property accessors do not.
i. exceptions, events, delegates
146. What is exception handling? When an exception occurs, the system searches for the nearest catch clause that can handle the exception, as determined by the run-time type of the exception. First, the current method is searched for a lexically enclosing try statement, and the associated catch clauses of the try statement are considered in order. If that fails, the method that called the current method is searched for a lexically enclosing try statement that encloses the point of the call to the current method. This search continues until a catch clause is found that can handle the current exception, by naming an exception class that is of the same class, or a base class, of the run-time type of the exception being thrown. A catch clause that doesn't name an exception class can handle any exception. Once a matching catch clause is found, the system prepares to transfer control to the first statement of the catch clause. Before execution of the catch clause begins, the system first executes, in order, any finally clauses that were associated with try statements more nested that than the one that caught the exception. Exceptions that occur during destructor execution are worth special mention. If an exception occurs during destructor execution, and that exception is not caught, then the execution of that destructor is terminated and the destructor of the base class (if any) is called. If there is no base class (as in the case of the object type) or if there is no base class destructor, then the exception is discarded.
147. Will finally block get executed if the exception had not occurred? Yes.
148. Explain what each segment of a try...catch...finally block does. The try block encloses code that is to be executed. If an exception is thrown, it can be caught in an appropriate catch block where code that will allow the application to handle the execution will be executed. The finally block contains any code that must be executed whether or not the exception is handled.
149. Will it go to finally block if there is no exception happened? 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.
150. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.
151. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.
152. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.
153. What’s a delegate? A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
154. What a delegate is and how one works? A delegate acts like a strongly typed function pointer. Delegates can invoke the methods that they reference without making explicit calls to those methods.
155. What’s a multicast delegate? It’s a delegate that points to and eventually fires off several methods.
156. What is Event Delegate?, clear syntax for writing a event delegate
// keyword_delegate.cs
// delegate declaration delegate void MyDelegate(int i);
class Program {
        public static void Main(){
                TakesADelegate(new MyDelegate(DelegateFunction));^K      }^K      public static void TakesADelegate(MyDelegate SomeFunction){^K            SomeFunction(21);^K      }^K      public static void DelegateFunction(int i){^K            System.Console.WriteLine("Called by delegate withnumber: {0}.", i);^K    }^K}
157. What is Asynchronous call and how it can be implemented using delegates?

158. How to create events for a control? What is custom events? How to create it?

k. garbage collection
159. What is Garbage Collection in .Net? Garbage collection process? The process of transitively tracing through all pointers to actively used objects in order to locate all objects that can be referenced, and then arranging to reuse any heap memory that was not found during this trace. The common language runtime garbage collector also compacts the memory that is in use to reduce the working space needed for the heap.
160. Briefly describe how garbage collection works. The garbage collector is a thread that runs in the background of managed .NET applications. It constantly traces the reference tree and attempts to find objects that are no longer referenced. When a nonreferenced object is found, its memory is reclaimed for later use.
161. How Garbage Collector (GC) Works? The methods in this class influence when an object is garbage collected and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method. Garbage collection consists of the following steps: a. The garbage collector searches for managed objects that are referenced in managed code. b. The garbage collector attempts to finalize objects that are not referenced. c. The garbage collector frees objects that are not referenced and reclaims their memory.
There generations in code. Generation 0 - just initialized objects, 1,2 - previous. If object survive GC No. of generation is increased. GC begins with objects 0, and released next generations only if the amount of memory is not enough.
162. What is the difference between the value-type variables and reference-type variables in terms of garbage collection? The value-type variables are not garbage-collected, they just fall off the stack when they fall out of scope, the reference-type objects are picked up by GC when their references go null.
163. What’s the difference between Java and .NET garbage collectors? Sun left the implementation of a specific garbage collector up to the JRE developer, so their performance varies widely, depending on whose JRE you’re using. Microsoft standardized on their garbage collection.
164. How do you enforce garbage collection in .NET? System.GC.Collect();
165. Why do we need to call CG.SupressFinalize? Requests that the system not call the finalizer method for the specified object.
public static void SuppressFinalize(^K   object obj^K);
The method removes obj from the set of objects that require finalization. The obj parameter is required to be the caller of this method. Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
166. Can you declare a C++ type destructor in C# like ~MyClass()? Yes, but what’s the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up, plus, it introduces additional load on the garbage collector. The only time the finalizer should be implemented, is when you’re dealing with unmanaged code.
167. What is the difference between Finalize and Dispose (Garbage collection) 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.
l. multithreading
168. How do you create threading in .NET? What is the namespace for that? The System.Threading namespace provides classes and interfaces that enable multithreaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex class for synchronizing mutually exclusive threads. System.Threading also provides classes for thread scheduling, wait notification, and deadlock resolution.
Mutex - new - begin, WaitAll, WaitAny,WaitOne - activizing, ReleaseMutex - releases.
m. tools
169. What is nmake tool? The Nmake tool (Nmake.exe) is a 32-bit tool that you use to build projects based on commands contained in a .mak file. usage : nmake -a all
170. What are the different .net tools which u used in projects?

n. others
171. What is Active Directory? What is the namespace used to access the Microsoft Active Directories? What are ADSI Directories? Active Directory Service Interfaces (ADSI) is a programmatic interface for Microsoft Windows Active Directory. It enables your applications to interact with diverse directories on a network, using a single interface. Visual Studio .NET and the .NET Framework make it easy to add ADSI functionality with the DirectoryEntry and DirectorySearcher components. Using ADSI, you can create applications that perform common administrative tasks, such as backing up databases, accessing printers, and administering user accounts. ADSI makes it possible for you to: a. Log on once to work with diverse directories. The DirectoryEntry component class provides username and password properties that can be entered at runtime and communicated to the Active Directory object you are binding to. b. Use a single application programming interface (API) to perform tasks on multiple directory systems by offering the user a variety of protocols to use. The DirectoryServices namespace provides the classes to perform most administrative functions. c. Perform "rich querying" on directory systems. ADSI technology allows for searching for an object by specifying two query dialects: SQL and LDAP. d. Access and use a single, hierarchical structure for administering and maintaining diverse and complicated network configurations by accessing an Active Directory tree. e. Integrate directory information with databases such as SQL Server. The DirectoryEntry path may be used as an ADO.NET connection string provided that it is using the LDAP provider. using System.DirectoryServices;
172. What are the different types of configuration files that the .NET Framework provides? Machine configuration file. This file is located in the %runtime installation path%\Config directory. The machine configuration file contains settings that affect all the applications that run on the machine. Application configuration file. This file contains the settings required to configure an individual application. ASP.NET configuration files are named Web.config, and application configuration files are named App.exe.config, where App.exe is the name of the executable. Security configuration file. The security configuration files contain security permissions for a hierarchy of code groups. The security configuration files define the enterprise-level, machine-level, and user-level security policies. The Enterprisesec.config file defines the security policies for the enterprise. The machine-level Security.config file defines the security policy for the machine, whereas the user-level Security.config file defines the security policy for a user.
173. What is InitializeComponent function? By default, Microsoft Visual Studio .NET creates an InitializeComponent function when you use Visual C# to create a new ASP.NET Web project. This function is used to associate Event objects with controls. To view the code, expand the generated code in Web Form Designer. You will notice a declaration similar to the following:
private void InitializeComponent(){
        this.Load += new System.EventHandler(this.Page_Load);
}
174. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.
175. How can you read 3rd line from a text file?
176. WebClient class and its methods?

2. Windows Forms (GUI,forms, controls, menus, print, accessibility)
a. GUI, general
177. You are creating an application for a major bank. The application should integrate seamlessly with Microsoft Office XP, be easy to learn, and instill a sense of corporate pride in the users. Name two ways you might approach these goals in the user interface. Design the user interface to mimic the look and feel of Microsoft Office XP, which will allow users of Office XP to immediately feel comfortable with the new application. Integration of the corporate logo and other visual elements associated with the company will aid in identification of the program with the company.
178. You are writing an application that needs to display a common set of controls on several different forms. What is the fastest way to approach this problem? Create a single form that incorporates the common controls, and use visual inheritance to create derived forms.
179. What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
180. How’s anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.
b. standard controls, menu
181. Write a simple Windows Forms MessageBox statement.
System.Windows.Forms.MessageBox.Show("Hello, Windows Forms");
182. You are designing a GUI application with a windows and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem? One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized.
183. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box? DataTextField
184. What is an extender provider, and what does one do? Extender providers are components that provide additional properties to controls on a form. Examples include the ErrorProvider, HelpProvider, and ToolTip components. They can be used to provide additional information about particular controls to the user in the user interface.
185. Explain how to use the HelpProvider component to provide help for UI elements. You can provide either a HelpString or a help topic for UI elements with the HelpProvider. The HelpProvider provides HelpString, HelpKeyWord, and HelpNavigator properties for each control on the form. If no value for the HelpProvider.HelpNameSpace is set, the HelpString will be provided as help. If the HelpNameSpace is set, the HelpProvider will display the appropriate help topic as configured by the HelpKeyWord and HelpNavigator properties. Help for a particular element is displayed when the element has the focus and the F1 key is pressed.
186. When you might implement a shortcut menu instead of a main menu? If every possible option is exposed on a main menu, the menu can become busy and hard to use. Shortcut menus allow less frequently used options to be exposed only in situations where they are likely to be used.
187. How do you create a separator in the Menu Designer? A hyphen ‘-’ would do it. Also, an ampersand ‘&’ would underline the next letter.
188. What class does Icon derive from? Isn’t it just a Bitmap with a wrapper name around it? No, Icon lives in System.Drawing namespace. It’s not a Bitmap by default, and is treated separately by .NET. However, you can use ToBitmap method to get a valid Bitmap object from a valid Icon object.
189. Describe two ways to set the tab order of controls on your form. You can set the tab order in Visual Studio by choosing Tab Index from the View menu and clicking each control in the order you desire. Alternatively, you can set the TabIndex property either in code or in the Properties window.
190. Before in my VB app I would just load the icons from DLL. How can I load the icons provided by .NET dynamically? By using System.Drawing.SystemIcons class, for example System.Drawing.SystemIcons.Warning produces an Icon with a warning sign in it.
191. What is meant by field-level validation and form-level validation? Field-level validation is the process of validating each individual field as it is entered into a form. Form-level validation describes the process of validating all of the data on a form before submitting the form.
192. How will you do Redo and Undo in a TextControl? Impossible, there is no such control (java).
c. user controls
193. Describe the three types of user-developed controls and how they differ. The three types of user-developed controls are inherited controls, user controls, and custom controls. An inherited control derives from a standard Windows Forms control and inherits the look, feel, and functionality of that control. User controls allow you to combine standard Windows Forms controls and bind them together with common functionality. Custom controls inherit from Control and are the most development-intensive kind of control. Custom controls must implement all their own code for painting and inherit only generic control functionality. All specific functionality must be implemented by the developer.
194. Describe the roles of Graphics, Brush, Pen, and GraphicsPath objects in graphics rendering. The Graphics object represents a drawing surface and encapsulates methods that allow graphics to be rendered to that surface. A Brush is an object that is used to fill solid shapes, and a Pen is used to render lines. A GraphicsPath object represents a complex shape that can be rendered by a Graphics object.
195. Describe the general procedure for rendering text to a drawing surface. You must first obtain a reference to a Graphics object. Next, create an instance of a GraphicsPath object. Use the GraphicsPath.AddString method to add text to the GraphicsPath. Then, call the Graphics.DrawPath or Graphics.FillPath to render the text.
196. Describe the role of the LicenseProvider in control licensing. The LicenseProvider controls license validation and grants run-time licenses to validly licensed components. The LicenseManager.Validate method checks for an available license file and checks against the validation logic provided by the specific implementation of LicenseProvider. You specify which LicenseProvider to use by applying the LicenseProviderAttribute.
197. Describe how to create a form or control with a nonrectangular shape. Set the Region property of the form or control to a Region object that contains the irregular shape. You can create a Region object from a GraphicsPath object.
198. I am constantly writing the drawing procedures with System.Drawing.Graphics, but having to use the try and dispose blocks is too time-consuming with Graphics objects. Can I automate this?  Yes, the code
System.Drawing.Graphics canvas = new System.Drawing.Graphics();^Ktry^K{ //some code }^Kfinally^K    canvas.Dispose();
is functionally equivalent to
using (System.Drawing.Graphics canvas = new System.Drawing.Graphics())^K{//some code^K}//canvas.Dispose() gets called automatically
199. How can you assign an RGB color to a System.Drawing.Color object? Call the static method FromArgb of this class and pass it the RGB values.
200. When displaying fonts, what’s the difference between pixels, points and ems? A pixel is the lowest-resolution dot the computer monitor supports. Its size depends on user’s settings and monitor size. A point is always 1/72 of an inch. An em is the number of pixels that it takes to display the letter M.
201. How would you create a non-rectangular window, let’s say an ellipse? Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
d. events
202. How do you trigger the Paint event in System.Drawing? Invalidate the current form, the OS will take care of repainting. The Update method forces the repaint.
203. With these events, why wouldn’t Microsoft combine Invalidate and Paint, so that you wouldn’t have to tell it to repaint, and then to force it to repaint? Painting is the slowest thing the OS does, so usually telling it to repaint, but not forcing it allows for the process to take place in the background.
204. If you wanted to prompt a user for input every time a form received the focus, what would be the best strategy for implementing this functionality? Write an event handler for the Activated event that implements the relevant functionality.
205. What’s the difference between Move and LocationChanged? Resize and SizeChanged? Both methods of class Control do the same, Move and Resize are the names adopted from VB to ease migration to C#.
e. printing
206. Briefly describe how to use the PrintDocument component to print a document. Discuss maintaining correct line spacing and multipage documents. The PrintDocument class exposes the Print method, which raises the PrintPage event. Code to render printed items to the printer should be placed in the PrintPage event handler. The PrintPage event handler provides the objects required to render to the printer in an instance of the PagePrintEventArgs class. Content is rendered to the printer using the Graphics object provided by PagePrintEventArgs. You can calculate correct line spacing by dividing the height of the MarginBounds property by the height of the font you are rendering. If your document has multiple pages, you must set the PagePrintEventArgs.HasMorePages property to true, which causes the PrintPage event to fire again. Because the PrintPage event handler retains no inherent memory of how many pages have been printed, you must incorporate all logic for printing multiple pages into your event handler.
f. accessibility
207. Briefly describe the five accessibility requirements of the Certified for Windows logo program. The five requirements are: a) Support standard system settings. This requires your application to be able to conform to system settings for colors, fonts, and other UI elements. b) Be compatible with High Contrast mode. This requirement can be met by using only the System palette for UI colors. c) Provide documented keyboard access for all UI features. Key points in this requirement are shortcut keys and accessible documentation.  d) Provide notification of the focus location. This requirement is handled primarily by the .NET Framework. e) Convey no information by sound alone. This requirement can be met by providing redundant means of conveying information.
3. Testing and Debugging WinApp
208. My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.
209. What debugging tools come with the .NET SDK? CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.
210. What is Break mode and what methods are available for navigating in Break mode? Break mode allows you to observe program execution on a line-by-line basis. You can navigate program execution in Break mode by using Step Into, Step Over, Step Out, Run To Cursor, and Set Next Statement.
211. What does the This window show in the debugger? It points to the object that’s pointed to by this reference. Object’s instance data is shown.
212. When would you use the Watch window? You would use the Watch window to observe the values of application variables while in Break mode.
213. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
214. What does assert() do? In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
215. You are deploying a beta version of a large application and want to collect performance data in text files while the application is in use. What is a strategy for enabling this scenario? Place Trace statements that report the data of interest throughout the application. Create a TextWriterTraceListener and add it to the Listeners collection. Create Trace switches that control when Trace statements are executed. Configure the TextWriterTraceListener to write output to a text file. Then, compile and deploy the application with Trace defined, and enable the Trace switches in the application .config file.
216. What is the use of trace utility?

217. What’s the difference between the Debug class and Trace class? Use Debug class for debug builds, use Trace class for both debug and release builds.
218. Why are there five tracing levels in System.Diagnostics.TraceSwitcher? The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.
219. Where is the output of TextWriterTraceListener redirected? To the Console or a text file depending on the parameter passed to the constructor.
220. What are three test cases you should go through in unit testing? Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).
221. When testing a method, should you test data that is known to be outside of the bounds of normal operation? Why or why not? Yes. In addition to testing normal data operation, you must test known bad input to ensure that your application can recover from input errors without a catastrophic application failure.
4. Deploying, Maintain. and Config.WinApps+ Nat lang.support
222. How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
223. So how do you retrieve the customized properties of a .NET application from XML .config file? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
224. Can you automate this process? In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.
225. What are the ways to deploy an assembly? An MSI installer, a CAB archive, and XCOPY command.
226. What’s the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code, the program runs within security sandbox, properly written app will not require additional security privileges.
227. What namespaces are necessary to create a localized application? System.Globalization, System.Resources.
228. Describe how to create localized versions of a form. To create a localized version of a form, set the Localizable property to true. Then set the Language property to the language/region for which you want to create the localized form. Make any localization-related changes in the UI. The changed property values will automatically be stored in resource files and loaded when the CurrentUICulture is set to the appropriate CultureInfo.
229. Explain how to convert data in legacy code page formats to the Unicode format. You can use the Encoding.Convert method to convert data between encoding types. This method requires instances of both encoding types and an array of bytes that represents the data to be converted. It returns an array of bytes in the target format. You can convert a string or array of chars to an array of bytes with the Encoding.GetBytes method and can convert an array of bytes back to chars with the Encoding.GetChars method.
230. Explain the difference between Globalization and Localization. Globalization refers to the application of culture-specific format to existing data. Localization refers to providing new culture-specific resources and retrieving the appropriate resources based on the culture setting.
231. Describe how to use code to retrieve resources at run time. You must first create an instance of the ResourceManager class that is associated with the assembly that contains the desired resource. You can then use the GetString method to retrieve string resources or the GetObject method to retrieve object resources.
232. Explain how to retrieve information from the configuration file at run time. How would you store information in the configuration file at design time? You must first create an instance of AppSettingsReader to read the configuration file. You can then call the GetValue method to read values represented in the configuration file. To add configuration file entries, you should create <add> elements in the <appSettings> node of the configuration file. In the <add> element, you should specify a value for the entry and a key that can be used to retrieve the entry. The value can be changed between executions of the application.
233. What are Satellite Assemblies? How you will create this? How will you get the different language strings? Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.
5. IIS
234. 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 aspnet_wp.exe.
235. Describe the role of inetinfo.exe, aspnet_isapi.dll and aspnet_wp.exe in the page loading process. 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 aspnet_wp.exe.
236. Where are the IIS log files stored? C:\WINDOWS\system32\Logfiles\W3SVC1 OR c:\winnt\system32\LogFiles\W3SVC1
237. What are the different IIS authentication modes in IIS and Explain? Difference between basic and digest authentication modes? IIS provides a variety of authentication schemes: a) Anonymous (enabled by default), b) Basic, c) Digest , d) Integrated Windows authentication (enabled by default), e) Client Certificate Mapping
Anonymous - 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.
a. 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.
b. 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.
238. How to configure the sites in Web server (IIS)?
239. IIS Isolation Levels? 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: a. 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).
b. 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).
c. 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.
6. ASP.Net - Web Apps (Forms,controls, events, namespaces, state info)
a. general
240. What are ASP.NET Web Forms? How is this technology different than what is available though ASP (1.0-3.0)? Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.
241. Asp.net and asp – differences?
ASP     Asp.Net         Code Render Block       Code Declaration Block                  Compiled                Request/Response        Event Driven                    Object Oriented - Constructors/Destructors, Inheritance, overloading..                  Exception Handling - Try, Catch, Finally                        Down-level Support                      Cultures                        User Controls                   In-built client side validation         Session - weren't transferable across servers   It can span across servers, It can survive server crashes, can work with browsers that don't support cookies            built on top of the window & IIS, it was always a separate entity & its functionality was limited.      its an integral part of OS under the .net framework. It shares many of the same objects that traditional applications would use, and all .net objects are available for asp.net's consumption.                  Garbage Collection                      Declare variable with datatype                  In built graphics support                       Cultures                242. What base class do all Web Forms inherit from? System.Web.UI.Page
243. Describe the life cycle of a Web application: When are Web forms instantiated and how long do they exist? A Web application starts with the first request for a resource within the application' s boundaries. Web forms are instantiated when they are requested. They are processed by the server and are abandoned immediately after the server sends its response to the client. A Web application ends after all client sessions end.
244. Where Visual Studio .NET stores Web application projects? Web application projects are stored in a new virtual folder for each project. The properties of that virtual folder determine where the files are physically stored. These properties can be viewed in IIS.
245. What determines the boundaries of a Web application? IIS determines Web application boundaries by the structure of the application' s virtual folders. A Web application boundary starts in the folder containing the start page of the application and it ends at the last subordinate folder or when it encounters another start page in a subordinate folder.
246. Describe the difference between inline and code behind - which is best in a loosely coupled solution? ASP.NET supports two modes of page development: Page logic code that is written inside <script runat=server> blocks within an .aspx file and dynamically compiled the first time the page is requested on the server. Page logic code that is written within an external class that is compiled prior to deployment on a server and linked "behind" the .aspx file at run time. Another one - code-behind(first line of WebForm1.aspx file): <%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="Asp1.WebForm1" %>
247. What’s the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only.
248. How server form post-back works (perhaps ask about view state as well).

249. Can the action attribute of a server-side <form> tag be set to a value and if not how can you possibly pass data from a form page to a subsequent page?

250. Explain the differences between Server-side and Client-side code? Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn’t have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.
251. What type of code (server or client) is found in a Code-Behind class? C# . - Code-behind class. A class that is accessed by an .aspx file, but resides in a separate file (such as a .dll or .cs file). For example, you can write a code-behind class that creates an ASP.NET custom server control, contains code that is called from an .aspx file, but does not reside within the .aspx file – then server.!!!
252. What are the major differences between Web and Windows applications? a. Web forms cannot use the standard Windows controls. Instead, they use server controls, HTML controls, user controls, or custom controls created specially for Web forms. b. Web applications are displayed in a browser. Windows applications display their own windows and have more control over how those windows are displayed. c. Web forms are instantiated on the server, sent to the browser, and destroyed immediately. Windows forms are instantiated, exist for as long as needed, and are destroyed. d. Web applications run on a server and are displayed remotely on clients. Windows applications run on the same machine they are displayed on.
253. What are the four main objects used in Web application programming? The four main objects in Web application programming are the Application, Page, Request, and Response objects.
254. When you build a project, what file(s) is created? a) ASP.NET Web Forms(.aspx), b) ASP.NET Web Services(.asmx), c) Classes and code-behind pages(.cs), d) Discovery files(.disco and .vsdisco), e) global application classes(global.asax), f) Resource files(.resx), g) Styles.css, h) Web.config file.
255. If you were given a Web page with an .aspx extension, what would you look for to verify that it is a Web Form? Web Forms consist of .aspx extension, Page attributes, Body attributes, and Form attributes.
256. If you were given a Web page with an .aspx extension, what would you look for to see if there are Web server controls? The runat=”server” attribute.
257. What is smart navigation? 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:  a) - eliminating the flash caused by navigation, b) persisting the scroll position when moving from page to page, c) persisting element focus between navigations, d) 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. Page.SmartNavigation Property
258. How would you get ASP.NET running in Apache web servers - why would you even do this?
259. Is it possible for me to change my aspx file extension to some other name? 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 <httpHandlers> tag <add verb="*" path="*.santhosh" type="System.Web.UI.PageHandlerFactory"/>
b. controls
260. Different types of HTML, Web and server controls
Feature Server controls HTML controls           Server events   Trigger control-specific events on the server.  Can trigger only page-level events on server (post-back)                State management        Data entered in a control is maintained across requests.        Data is not maintained; must be saved and restored using page-level scripts             Adaptation      Automatically detect browser and adapt display as appropriate.  No automatic adaptation; must detect browser in code or write for least common denominator              Properties      The .NET Framework provides a set of properties for each control. Properties allow you to change the control' s appearance and behavior within server-side code.        HTML attributes only            Display text    Label, TextBox, Literal Label, Text Field, Text Area, Password Field            Display tables  Table, DataGrid Table           Select from list        DropDownList, ListBox, DataList, Repeater       List Box, Dropdown              Perform commands        Button, LinkButton, ImageButton Button, Reset Button, Submit Button             Set values      CheckBox, CheckBoxList, RadioButton, RadioButtonList    Checkbox, Radio Button          Display images  Image, ImageButton      Image           Navigation      Hyperlink       none (use <a> tags in text)             Group controls  Panel, Placeholder      Flow Layout, Grid Layout                Work with dates Calendar        none            Display ads     AdRotator       none            Display horizontal rules        Literal Horizontal Rule         Get filenames from client       none    File Field              Store data on page      (provided by state management)  Input Hidden            Validate data   RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, CustomValidator,ValidationSummary none (use page-level)           261. What is the main difference between the Button server control and the Button HTML control? When clicked, the Button server control triggers an ASP.NET Click event procedure on the server. The Button HTML control triggers the event procedure indicated in the button' s onclick attribute, which runs on the client.
262. How do you get several RadioButton controls to interoperate on a Web form so that only one of the RadioButtons can be selected at once? Set the GroupName property of each RadioButton to the same name.
263. What tags do you need to add within the asp:datagrid tags to bind columns manually? Column tag and an ASP:databound tag.
264. What is the difference between control and component?
265. What are server controls? ASP.NET server controls are components that run on the server and encapsulate user-interface and other related functionality. They are used in ASP.NET pages and in ASP.NET code-behind classes.
266. What is different between User Control and Web Control and Custom Control? Web user controls. These combine existing server and HTML controls by using the Visual Studio .NET Designer to create functional units that encapsulate some aspect of the user interface. User controls reside in content files, which must be included in the project where they are used. Composite custom controls. These create new controls from existing server and HTML controls. Though similar to user controls, composite controls are created in code rather than visually, and therefore can be compiled into an assembly (.dll), which can be shared between multiple applications and used from the Toolbox in Visual Studio .NET. Rendered custom controls. These create entirely new controls by rendering HTML directly rather than using composition. These controls are compiled and can be used from the Toolbox, just like composite controls, but you must write extra code to handle tasks that are performed automatically in composite controls.
Web user controls       Web custom controls             Easier to create        Harder to create                Limited support for consumers who use a visual design tool      Full visual design tool support for consumers           A separate copy of the control is required in each application  Only a single copy of the control is required, in the global assembly cache             Cannot be added to the Toolbox in Visual Studio Can be added to the Toolbox in Visual Studio            Good for static layout  Good for dynamic layout         267. Briefly describe the best uses for each of the three types of Web controls by completing the following sentences: Create a user control when you want to…quickly create a group of controls that can be reused throughout a project to perform some logical unit of work.Create a composite custom control when you want to…combine one or more existing controls into a compiled assembly that can be easily reused in many different projects.Create a rendered control when you want to…build an entirely new control that can be compiled into an assembly for use in multiple projects.
268. How is deriving important to creating custom Web controls? Both composite and rendered custom controls are derived from the WebControl base class. That class provides the methods that you override to create the appearance of the custom control.
269. What is the most important method to override when creating a composite custom control? You override the CreateChildControls method to add existing controls to a composite custom control.
270. What is the most important method to override when creating a rendered control? You override the Render method when creating a rendered custom control.
271. How is raising a post-back event in a composite control different from raising a post-back event in a rendered control? In a composite control, you can use one of the contained controls to raise a post-back event. In a rendered control, you must implement the IPostBackEventHandler interface and write a client-side script to raise a post-back event.
272. How do you implement postback with a text box? What is postback and usestate? Make AutoPostBack property to true
273. What property do you have to set to tell the grid which page to go to when using the Pager object?
274. How do you reference a user control from an ASP.NET Web Form? Use @Control directive.
275. How can you use a user control in two different Web applications? To use a user control in multiple Web applications, the user control must be copied to the virtual root folder of each Web application.
276. How can we create Tree control in asp.net? There are some products for sale or for free  - see Internet.
277. How can we create pie chart in asp.net? Dundas - .Net charts (library).
c. validation controls
278. What are validators? Name the Validation controls in asp.net? How do you disable them? Will the asp.net 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 asp.net:
RequiredFieldValidator Control - to ensure that the user does not skip an entry.,
CompareValidator Control - to compare a user's entry against a constant value, against a property value of another control, or against a database value using a comparison operator (less than, equal, greater than, and so on),
RangeValidator Control - to check that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. Boundaries are expressed as constants.,
RegularExpressionValidator Control - to check that the entry matches a pattern defined by a regular expression. This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on.,
CustomValidator Control - to create custom server and client validation code,
ValidationSummary Control - displays a summary of all validation errors for all validation controls on a page.
279. Should validation (did the user enter a real date) occur server-side or client-side? Why? Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine.
280. Why does ASP.NET perform validation on both the client and the server? Client-side validation helps avoid round trips to the server. Validating on the client makes sure that the data is valid before it is submitted, in most cases. However, because validation might be turned off (or maliciously hacked) on the client, data must be revalidated on the server side. This provides full assurance that the data is valid while avoiding as many round trips as possible.
281. Which two properties are on every validation control? ControlToValidate & ErrorMessage properties
282. Which control would you use if you needed to make sure the values in two different controls matched? Use the CompareValidator control to compare the values of 2 different controls.
283. What types of validation would you use to verify that a user entered a valid customer number? You would use a RequiredFieldValidator and a RegularExpressionValidator. If you have access to a list of expected customer numbers, you could replace the RegularExpressionValidator with a CustomValidator that checked the list.
284. For the following questions, you will select type of validation control(s) that should be used for each scenario. CompareValidator, CustomValidator, RangeValidator, RegularExpressionValidator, RequiredFieldValidator, ValidationSummary. Given the following user input fields, what kind of validation control(s) would you use?
a. The user’s age
b. The user’s telephone number
c. The user’s password, which is entered twice.
d. Whether an entered number is prime.
e. Whether all of the fileds in a form are correctly filled in.
f. Whether the date format is correct
g. Whether a new employee’s requested e-mail address matches the company policy.
285. What data type does the RangeValidator control support? Integer, String and Date.
d. events
286. Order of events in an asp.net page? Control Execution Lifecycle?
Phase   What a control needs to do      Method or event to override             Initialize      Initialize settings needed during the lifetime of the incoming Web request.     Init event (OnInit method)              Load view state At the end of this phase, the ViewState property of a control is automatically populated as described in Maintaining State in a Control. A control can override the default implementation of the LoadViewState method to customize state restoration.  LoadViewState method            Process postback data   Process incoming form data and update properties accordingly.   LoadPostData method (if IPostBackDataHandler is implemented)            Load    Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data. Load event
(OnLoad method)         Send postback change notifications      Raise change events in response to state changes between the current and previous postbacks.    RaisePostDataChangedEvent method (if IPostBackDataHandler is implemented)               Handle postback events  Handle the client-side event that caused the postback and raise appropriate events on the server.       RaisePostBackEvent method(if IPostBackEventHandler is implemented)              Prerender       Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost.        PreRender event ^K(OnPreRender method)           Save state      The ViewState property of a control is automatically persisted to a string object after this stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a control can override the SaveViewState method to modify the ViewState property. SaveViewState method            Render  Generate output to be rendered to the client.   Render method           Dispose Perform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.       Dispose method          Unload  Perform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event.   UnLoad event (On UnLoad method)         Note   To override an EventName event, override the OnEventName method (and call base. OnEventName).
287. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It’s a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events.
288. In what order do the events of an ASPX page execute. As a developer is it important to understand these events? Every Page object (which your .aspx page is) has nine events, most of which you will not have to worry about in your day to day dealings with ASP.NET. The three that you will deal with the most are: Page_Init, Page_Load, Page_PreRender.
289. What methods are fired during the page load? Init() - when the page is instantiated, Load() - when the page is loaded into server memory, PreRender() - the brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.
290. What’s a bubbled event? When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main DataGrid event handler to take care of its constituents.
291. Suppose you want a certain ASP.NET function executed on MouseOver over a certain button. Where do you add an event handler? It’s the Attributes property, the Add function inside that property. So btnSubmit.Attributes.Add("onMouseOver","someClientCode();") A simple "Javascript:ClientCode();” in the button control of the .aspx page will attach the handler (javascript function)to the onmouseover event.
292. Application and Session Events The ASP.NET page framework provides ways for you to work with events that can be raised when your application starts or stops or when an individual user's session starts or stops:  Application events are raised for all requests to an application. For example, Application_BeginRequest is raised when any Web Forms page or XML Web service in your application is requested. This event allows you to initialize resources that will be used for each request to the application. A corresponding event, Application_EndRequest, provides you with an opportunity to close or otherwise dispose of resources used for the request. Session events are similar to application events (there is a Session_OnStart and a Session_OnEnd event), but are raised with each unique session within the application. A session begins when a user requests a page for the first time from your application and ends either when your application explicitly closes the session or when the session times out.  You can create handlers for these types of events in the Global.asax file.
293. How does ASP.NET framework maps client side events to Server side events.
294. You've defined one page_load event in aspx page and same page_load event in code behind how will prog run?
295. What is AutoEventWireup attribute for? Indicates whether page events are automatically enabled.
<configuration>
   <system.web>
      <pages
         buffer="true"
         enableSessionState="true"
         autoEventWireup="true"/>
   </system.web>
</configuration>
e. state info
296. What is the role of global.asax.? What are the three categories of events that are handled in the global.asax file? a) Events that are fired when a page is requested, b) Events that are fired when the requested page is sent, c) Conditional application events.
297. Where is global.asax file of an application located? It is located in the virtual root of the application.
298. Can there be more than one global.asax file for a single Web application? No. Ever ASP.NET Web application supports one global.asax file per Web application.
299. How do you preserve persistent data, such as simple variables, in a Web application? You can preserve data in state variables, such as ApplicationState, SessionState, or ViewState.
300. Where would you save the following data items so that they persist between requests to a Web form? a) A control created at run time - Save controls created at run time in the Page object' s ViewState. b) An object that provides services to all users - Save objects that provide services to all users in the Application state. c) User preferences - Save user preferences in SessionState.
301. Where do we store our connection string in asp.net application?
302. Difference between ASP Session and ASP.NET Session? asp.net session supports cookie less session & it can span across multiple servers.
303. What does the "EnableViewState" property do? Why would I want it on or off? Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip, then you do not need the control to maintain it’s view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.
304. What are the disadvantages of viewstate/what are the benefits? Because Web Forms pages make a round trip to the server each time processing is required, they present unique problems in how to save the values in controls and on the page. A server control's view state is the accumulation of all its property values. In order to preserve these values across HTTP requests, ASP.NET server controls use this property, which is an instance of the StateBag class, to store the property values. The values are then passed as a variable to a hidden field when subsequent requests are processed.
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.
305. What is the difference between a temporary cookie and a persistent cookie? Temporary cookies, also called the session or non-persistent cookies, exist only in the memory of the browsers. When the browser is shut down, any temporary cookies that were added to the browser are lost. Persistent cookies are similar to temporary cookies, except that persistent cookies have a definite expiration period. When a browser requests a page that creates a persistent cookie, the browser saves that cookies to the user’s hard disk.
306. How do you create a permanent cookie?  Setting the Expires property to MinValue means that the Cookie never expires.
307. What are the contents of cookie?
**
308. How do you turn off cookies for one page in your site? Use the Cookie.Discard Property which Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.
309. What is cookie less session? How it works? By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following: <sessionState cookieless="true" />
310. How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are the limits? By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session data in an external process, which can even reside on another machine. To enable this feature:
a) 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
b) Set the mode attribute of the <sessionState> section to "StateServer".
c) 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):
 <sessionState mode="StateServer" stateConnectionString="tcpip=localhost: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.
311. What method do you use to explicitly kill a user s session? The Abandon method destroys all the objects stored in a Session object and releases their resources. If you do not call the Abandon method explicitly, the server destroys these objects when the session times out. Syntax: Session.Abandon
312. What is State Management in .Net and how many ways are there to maintain a state in .Net? What is view state? Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip.  To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips. However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options: a) View State, b) Hidden Form Fields, c) Cookies, d) Query Strings^KServer-Based State Management Options a) Application State, b) Session State, c) Database Support
313. When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade? Maintaining state using database technology is a common practice when storing user-specific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted.
314. What are the page level transaction and class level transaction?

315. Various steps taken to optimize a web based application (caching, stored procedure etc.)
316. How to do Caching in ASP? <%@ 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            <%@ OutputCache Duration="60" VaryByParam="none" %>^K<%@ OutputCache Duration="60" VaryByParam="*" %>^K<%@ OutputCache Duration="60" VaryByParam="name;age" %>^KThe OutputCache directive supports several other cache varying options
a) VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.)
b) VaryByControl - for user controls, maintain separate cache entry for properties of a user control
c) VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplication derived class
317. How do you set cache options for a Web application? Use the FrontPage Server Extensions in IIS to set the page caching options for a Web application.
318. What is the difference between application and cache variables?

f. CSS, formatting output
319. How do you use css in asp.net? 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:
<LINK REL="STYLESHEET" TYPE="text/css" HREF="MyStyles.css">
MyStyles.css is the name of your external CSS style sheet.
320. What is the advantage of using CSS rather than in-line styles for formatting a Web application? Using CSS allows you to maintain formatting separately from the content of your Web forms, so changes are easier to make and consistency is easier to maintain.
321. Why would you create a style for a class rather than for an HTML element? You create style classes when you want to apply the same formatting to different types of elements within an application. For example, you might want to create an emphasis style class that applies the same formatting to any text, control, heading, or image that you want to draw the user' s attention to.
322. How do CSS and XSL relate to each other when it comes to formatting a Web application? CSS and XSL are complementary techniques for formatting. CSS determines the font, color, size, background, and other appearance aspects of HTML elements on a Web page. XSL is used to transform XML files into HTML output. In this way, XSL controls the position and appearance of items based on their content. Used together, XSL performs the high-level tasks of composition and layout while CSS performs the low-level tasks of applying fonts, colors, and other appearance features.
323. What are the differences between HTML and XML? a) HTML uses predefined element names, such as <p> and <br>. In XML, you create your own element names to identify hierarchical nodes of data. b) XML syntax is much stricter than HTML: elements must always have end-tags, element names are case sensitive, attribute values must always be enclosed in quotation marks, and nested elements must be terminated within their parent elements. c) XML identifies data conceptually based on the data' s content, rather than based on the type of formatting to apply.
g. mail
324. Write the HTML for a hyperlink that will send mail when the user clicks the link.
<a href="mailto:you@microsoft.com?SUBJECT=Sending from a client&BODY=Some  message text."> Send mail</a>
325. How do I send an email message from my ASP.NET page? You can use the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail class to send email in your ASPX pages. Below is a simple example of using this class to send mail in C# and VB.NET. In order to send mail through our mail server, you would want to make sure to set the static SmtpServer property of the SmtpMail class to mail-fwd.
h. others
326. Which method do you use to redirect the user to another page without performing a round trip to the client? Server.Transfer()
327. What is wrong with the following line of code? Server.Transfer("Default.htm");
You can' t use the Transfer method with HTML pages. It works only with .aspx pages.
328. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist across the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical location (page name and query string as well). Context.Items loses the persistance when navigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they’re difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.
329. What’s the difference between Response.Write() and Response.Output.Write()? The latter one allows you to write formatted output.
330. How do I upload a file from my ASP.NET page? In order to perform file upload in your ASP.NET page, you will need to use two classes: the System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile class. The HtmlInputFile class represents and HTML input control that the user will use on the client side to select a file to upload. The HttpPostedFile class represents the uploaded file and is obtained from the PostedFile property of the HtmlInputFile class. In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:
<form id="upload" method="post" runat="server" enctype="multipart/form-data">
Also, remember that the /data directory is the only directory with Write permissions enabled for the anonymous user. Therefore, you will need to make sure that your code uploads the file to the /data directory or one of its subdirectories.
331. How do you specify whether your data should be passed as Query string and Forms (Mainly about POST and GET) Through attribute tag of form tag.
332. What is the other method, other than GET and POST, in ASP.NET?

333. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one? iHTTPModule is in System.Web namespace. The System.Web namespace supplies classes and interfaces that enable browser/server communication. Interface iHTTPModule provides module initialization and disposal events to the inheriting class.
One of ASP.NET’s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.
334. Why can' t you open a new browser window from within server code? Server code executes on the server, whereas the new window is created on the client. You need to use client-side code to do things that affect the client, such as upload files, display new windows, or navigate back in history.
335. How would you display a page in a new window with a client-side script? You can open a new window using the DOM window object. For example, the following HTML Button control opens a Help page in a new window: <button id="butHelp" onclick="window.open('help.aspx', 'help', 'height=200,width=300')"> Help </button> 
336. How do you display a page in one frame from a hyperlink in another frame? Use the <a> element' s target attribute to specify the frame to display the page. For example, the following hyperlink displays a page in the main frame of a frameset:
<a href="AllTheAnswers.aspx" target="main">Show the answers!</a>
337. How do you reuse a database connection component throughout a Web application? Add the database connection component to the Global.asax file, then create a state variable in the Application_Start or Session_Start event procedures to share the connection with the Web forms in the application.
338. What is SQL injection? 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]^KThis would execute the following query against the users table:
select count(*) from users where userName='' or 1=1 --' and userPass=''
339. How does ASP.NET know to which page you have to be redirected when using the RedirectFromLoginPage method? The RedirectFromLoginPage method redirects authentication users back to the original URL that they requested.
340. Describe session handling in a webfarm, how does it work and what are the limits? StateServer - Solve the session state loss problem in InProc mode. Allows a webfarm to store session on a central server. Single point of failure at the State Server.
341. Which HTML sound and video elements are supported by most browsers? Most browsers support these HTML elements: bgsound, img, and embed.
342. What central feature does HTML+TIME provide that is not available with other animation techniques? HTML+TIME allows you to synchronize timed events on a page.
343. List two ways to create a new timeline using HTML+TIME. a) Use one of the timeline elements, such as t:SEQ, t:EXCL, or t:PAR. b) Add a TIMECONTAINER attribute to a standard HTML element.
6. Maintaining and configuring WebApps
344. Which files can you use to configure an ASP.NET Web application? Machine.config and Web.config
345. What is the use of web.config? Difference between machine.config and Web.config? 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\<version>\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 Forbidden). 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).
346. Which ASP.NET configuration options are supported in the ASP.NET implementation on the shared web hosting platform? 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): - browserCaps, clientTarget, pages, customErrors, globalization, authorization, authentication, webControls, webServices
347. What is the use of sessionState tag in the web.config file? Configuring session state: Session state features can be configured via the <sessionState> 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: <sessionState timeout="40" />
348. How do you turn off SessionState in the web.config file? In the system.web section of web.config,  you should locate the httpmodule tag and you simply disable session by doing a remove tag with attribute name set to session.
<httpModules>^K<remove name="Session” />^K</httpModules>
349. What are the different modes for the sessionstates in the web.config file?
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.               350. What is main difference between Global.asax and Web.Config? ASP.NET uses the global.asax to establish any global objects that your Web application uses. The .asax extension denotes an application file rather than .aspx for a page file. Each ASP.NET application can contain at most one global.asax file. The file is compiled on the first page hit to your Web application. ASP.NET is also configured so that any attempts to browse to the global.asax page directly are rejected. However, you can specify application-wide settings in the web.config file. The web.config is an XML-formatted text file that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web site, compilation options for the ASP.NET Web pages, if tracing should be enabled, etc.
7. Building, deploying & Globalizing WebApps
351. What permissions do Web applications run under by default? By default, Web applications run as the ASPNET user, which has limited permissions equivalent to the Users group.
352. How would ASP and ASP.NET apps run at the same time on the same server? If you haven't the time or resources to convert or re-write legacy code to the new platform you can make use of .NET's interoperability features to re-use this legacy code until such time as the resources are available or the application naturally reaches the end of its useful life. Several types of code can be re-used: a) ASP code will run alongside ASP.NET pages, b) ActiveX controls can be placed on web forms , c) COM and COM+ components can be employed in .NET code, d) Platform invoke can be used to directly call the Windows API
353. How do u deploy your asp.net application?

354. Why is the Machine.config file important to deployed Web applications? The Machine.config file controls many aspects of how Web applications run, including how processes are recycled, what types of request queue limits are imposed, and what interval is used when checking if users are still connected.
355. How does deploying to a Web farm or a Web garden affect Session state in a Web application? Web applications that are deployed to a Web farm or a Web garden need to identify a Session state provider in their Web.config file. This is because a single client' s requests can be directed to different processes over the course of his or her session. The Session state provider allows each different process to access the client' s Session state.
356. Where do you store the information about the user’s locale? System.Web.UI.Page.Culture
357. What is the difference between the CurrentCulture property and the CurrentUICulture property? The CurrentCulture property affects how the .NET Framework handles dates, currencies, sorting, and formatting issues. The CurrentUICulture property determines which satellite assembly is used when loading resources.
358. How do you detect the user' s culture? Use the Request object' s UserLanguages array. The value at element 0 corresponds to one of the culture codes used by the CultureInfo class. For example: SLang = Request.UserLanguages(0)
359. What is a neutral culture? Neutral cultures represent general languages without region-specific differences, such as currency. For example, the “es” culture code represents Spanish.
360. How does character encoding affect file formats? When using non-ASCII characters in a Web form, you must save the file with a specific character encoding, such as UTF-8. ASP.NET can automatically detect UTF-8 file encoding if the file is saved with a signature; otherwise, you need to specify the file encoding used in the fileEncoding attribute of the globalization element in Web.config.
361. What are the three main steps to deploying an ASP.NET Web application? Copy files locally or FTP files remotely, Configure the target folder as virtual directory in IIS, Copy all necessary files, including the \bin directory and content
8. Testing & debugging web apps
a. debugging
362. How do you debug an ASP.NET Web application? Attach the aspnet_wp.exe process to the DbgClr debugger.
363. How can you debug an ASP page, without touching the code?
364. What is the difference between the Debug and Trace classes? Under the default environment settings, code using the Debug class is stripped out of release builds, while code using the Trace class is left in. The classes are otherwise equivalent.
b. exceptions
365. How can u handle Exceptions in Asp.Net? List two different exception-handling approaches in ASP.NET Web applications. Exceptions can be handled in exception-handling blocks using the try, catch, and finally keywords. They can also be handled using Error event procedures at the Global, Application, or Page levels using the Server object' s GetLastError and ClearError methods.
366. How can you handle UnManaged Code Exceptions in ASP.Net?
367. Asp.net - How to find last error which occurred? Server.GetLastError();
Exception LastError; String ErrMessage;^KLastError = Server.GetLastError();^Kif (LastError != null) ErrMessage = LastError.Message;^Kelse ErrMessage = "No Errors";^KResponse.Write("Last Error = " + ErrMessage);
c. testing, tracing
368. Describe the purpose of error pages and why they are needed. Because Web applications run over the Internet, some exceptions occur outside the scope of the application. This means that your application cannot respond directly to these exceptions. These types of exceptions are identified by HTTP response codes, which IIS can respond to by displaying custom error pages listed in your application' s Web.config file.
369. Explain why tracing helps with exception handling. Tracing allows you to record unusual events while your application is running, without users being aware of it. If an unanticipated exception occurs, your application can write a message to the trace log, which helps you diagnose problems during testing and after deployment.
370. Which is the namespace used to write error message in event Log File? System.Diagnostics.EventLog
(CreateEventLog, WriteEntry
371. How do unit, integration, and regression testing relate to each other? Unit testing is the foundation that ensures that each piece of code works correctly. Integration testing extends this concept by verifying that pieces work together without errors. Regression tests are made up of the existing unit and integration tests, which are run on a regular schedule to assure that new code did not break previously working code.
372. Why is load testing likely to be more important for a Web application than for a stand-alone Windows application? Because Web applications can be public on the Internet, they can have hundreds, thousands, or even millions of users. Load tests let you simulate the expected demand to locate resource conflicts, performance bottlenecks, and other problems that aren' t apparent in single-user tests.
9. Windows Services
a. general
373. Explain Windows service. You often need programs that run continuously in the background. For example, an email server is expected to listen continuously on a network port for incoming email messages, a print spooler is expected to listen continuously to print requests, and so on.
374. What’s the Unix name for a Windows service equivalent? Daemon.
375. What are the states of a service application? The states in which a service application can remain are running, paused, stopped, and pending.
376. So basically a Windows service application is just another executable? What’s different about a Windows service as compared to a regular application? Windows services must support the interface of the Service Control Manager (SCM). A Windows service must be installed in the Windows service database before it can be launched.
377. What are the different types of Windows services? Windows services are of two types: Win32OwnProcess and Win32ShareProcess services. Each Win32OwnProcess runs in its own process space, whereas Win32ShareProcess services share a process space with other services.
378. Can you share processes between Windows services? Yes.
379. How is development of a Windows service different from a Windows Forms application? A Windows service typically does not have a user interface, it supports a set of commands and can have a GUI that’s built later to allow for easier access to those commands.
b. development
380. What are the tasks that you perform to create a Windows service? These tasks are performed when creating a Windows service: a. Create a blank Windows service by using the Windows Service template for Visual Studio .NET. b. Change the default properties of the Windows Service template according to your requirements. c. Write code in the service application project to handle various events. d. Add installers to your service application. e. Install your service application by using the installation tools.
381. When developing a Windows service for .NET, which namespace do you typically look in for required classes? System.ServiceProcess. The classes are ServiceBase, ServiceProcessInstaller, ServiceInstaller and ServiceController.
382. How do you add functionality to a service application? To add functionality to a service application, you override the OnStart and OnStop methods of the ServiceBase class. You can also override the OnPause, OnContinue, and OnCustomCommand methods of the ServiceBase class to increase the functionality of a service application.
383. I want to write a Windows service that cannot be paused, only started and stopped. How do I accomplish that? Set CanPauseAndContinue attribute to false.
384. Can I write an MMC snap-in for my Windows service? Yes, use classes from the System.Management.Instrumentation namespace.
385. How do you log custom information in the default event logs? To enable your service application to access the default event logs and write information in them, set the AutoLog property of a service application to False. You then use the WriteEntry method of the EventLog class log to write information in the default event logs.
386. What are the steps to run custom commands on your service application? The steps to run custom commands on your service application are a) Create a Windows application that you use to control your service application. b) Create a method that calls the ServiceController.ExecuteCommand method in the Windows application. c) Override the OnCustomCommand method in your service application to specify the tasks that you want your service application to perform.
c. SCM, running,debugging
387. What does SCM do? SCM is Windows Service Control Manager. Its responsibilities are as follows: 1)-Accepts requests to install and uninstall Windows services from the Windows service database. 2) -To start Windows services either on system startup or requested by the user. 3) -To enumerate installed Windows services. 4) -To maintain status information for currently running Windows services. 5) -To transmits control messages (such as Start, Stop, Pause, and Continue) to available Windows services. 6) -To lock/unlock Windows service database.
388. What administrative tasks can you perform on your service using the SCM? You can perform the following administrative tasks using the SCM: a) Change the state of a service, b) Specify how to start a service, c) Specify the recovery actions in case of a service failure, d) Specify a user account for a service, e) View service dependencies
389. How do you handle Start, Pause, Continue and Stop calls from SCM within your application? By implementing OnStart, OnPause, OnContinue and OnStop methods.
390. Describe the start-up process for a Windows service. Main() is executed to create an instance of a Web service, then Run() to launch it, then OnStart() from within the instance is executed.
391. How can you see which services are running on a Windows box? Admin Tools -> Computer Management -> Services and Application -> Services. You can also open the Computer Management tool by right-clicking on My Computer and selecting Manage from the popup menu.
392. How do you start, pause, continue or stop a Windows service off the command line? net start ServiceName, net pause ServiceName and so on. Also sc.exe provides a command-line interface for Windows services.
393. What are the steps to attach a debugger to your service application? The steps to attach a debugger to your service application are: a) Start your service application using the SCM. b) Choose Processes from the Debug menu. c) Select Show System Processes. d) Select the process for your service application and click Attach. The Attach To Process dialog box appears. e) Select Common Language Runtime, click OK to specify a debugger, and close the Attach To Process dialog box.
394. Where’s Windows service database located? HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services
d. permissions
395. How do you give a Windows service specific permissions? Windows service always runs under someone’s identity. Can be System or Administrator account, but if you want to restrict the behavior of a Windows service, the best bet is to create a new user account, assign and deny necessary privileges to that account, and then associate the Windows service with that new account.
396. How do you specify the security context of a user account within which a service application runs? You use the Account property of the ServiceProcessInstaller class to specify the security context for your service application. To specify the security context of a user account, set the Account property to User. You then need to specify the user name and password of a user account when you install the service application.
e. install
397. Why do you need to include installers in your service application? The installers enable you to install a Windows service and resources, such as custom logs and performance counters, that a service application uses on a computer. The installers automatically install these resources when you install a service application using the Installutil tool.
398. What application do you use to install a Windows service? installutil.exe
399. Why do you need to add instances of both the ServiceProcessInstaller and ServiceInstaller classes to install your service application? A service application can contain more than one service. The methods of the ServiceProcessInstaller class perform the tasks that are common for all the services within a service application, such as writing entries in the system registry for all the services within the service application. The ServiceInstaller class performs tasks specific to a service, such as creating an entry for a service in the registry of a computer.
400. I am trying to install my Windows service under NetworkService account, but keep getting an error. The LocalService and NetworkService accounts are only available on Windows XP and Windows Server 2003. These accounts do not exist on Windows 2000 or older operating systems.
10. Serviced Components (COM,COM+)
a. general
401. Define scalability. The application meets its requirement for efficiency even if the number of users increases.
402. Define reliability. The application generates correct and consistent information all the time.
403. Define availability. Users can depend on using the application when needed.
404. Define security. The application is never disrupted or compromised by the efforts of malicious or ignorant users.
405. Define manageability. Deployment and maintenance of the application is as efficient and painless as possible.
406. How is COM+ related to the DNA architecture? Windows DNA provides the infrastructure and services that enable you to create and deploy applications based on the three-tier architecture. COM+ services, which are an integral part of Windows DNA, include services such as transactions, queued components (QC), security, loosely coupled events, JIT activation, and object pooling.
407. What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling? Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached. Following are important differences between object pooling and connection pooling: Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.) COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.
408. Briefly explain the use of the following COM+ services: JIT activation, Queued components, Object pooling Just-in-time activation. The Just-In-Time (JIT) Activation services of COM+ ensure that the client application has references to objects as long as they require them. As a result, the client application does not need to use the valuable memory resources of the server to save the object references. Queued components. The Queued Component service of COM+ is based on the Microsoft Message Queue Server (MSMQ) model that is a part of Windows 2000 and Windows XP. MSMQ is a middle-tier service that facilitates the asynchronous delivery of messages to named queues. The MSMQ system queues up the method calls and executes them automatically as and when the component is available. You can, therefore, use queued components to execute client methods even after the component is unavailable or offline, ensuring the continuous running of a distributed application. Object pooling. COM+ provides an automated service for configuring a component so that it can maintain ready-to-use and active object instances in a pool to process client requests. To configure and monitor the pool, you specify characteristics such as the pool size and the creation request time-out values. Next, the COM+ service is responsible for managing the pool and ensuring the activation and reuse of the pool objects according to the configured specifications.
409. What is the new three features of COM+ services, which are not there in COM (MTS)?

410. Explain object pooling. With object pooling, COM+ creates objects and keeps them in a pool, where they are ready to be used when the next client makes a request. This improves the performance of a server application that hosts the objects that are frequently used but are expensive to create.
411. Explain queued components. The queued components service enables you to create components that can execute asynchronously or in disconnected mode. Queued components ensure availability of a system even when one or more sub-systems are temporarily unavailable. Consider a scenario where salespeople take their laptop computers to the field and enter orders on the go. Because they are in disconnected mode, these orders can be queued up in a message queue. When salespeople connect back to the network, the orders can be retrieved from the message queue and processed by the order processing components on the server.
412. Explain loosely coupled events. Loosely coupled events enable an object (publisher) to publish an event. Other objects (subscribers) can subscribe to an event. COM+ does not require publishers or subscribers to know about each other. Therefore, loosely coupled events greatly simplify the programming model for distributed applications.
413. Is the COM architecture same as .Net architecture?  What is the difference between them (if at all there is)? .NET provides a completely new approach to creating and deploying components. They are also known as Assemblies. With COM , the developer had to register the component on the server ( system registry). With .NET assemblies, the assembly file encapsulates all the meta data required in special sections called Manifests. In .NET , for an assembly to be available to the client , it only has to be in the same directory as the client application. The developer doesn't have to register the component on the server and several versions of the same component can safely co-exist together on the same machine. Creating a .NET assembly is a lot like creating a VB6-COM component, the developer only has to worry about the business logic, all the background plumbing code is generated by the .NET, also since the .NET runtime maintains garbage collection externally, the component does not have to worry about keeping it's reference count as was done in COM with the help of the IUnknown Interface. Microsoft provides developers with tools to use .NET assemblies and COM together. The Type Library Importer (TLBIMP.exe) utility creates .NET wrappers for the COM components. The Type Library Exporter (TLBEXP.exe) utility creates COM wrappers for .NET components.
414. Are COM objects managed or unmanaged? Since COM objects were written before .NET, apparently they are unmanaged.
415. Can we copy a COM dll to GAC folder?^K**
416. Can .NET Framework components use the features of Component Services? Yes, you can use the features and functions of Component Services from a .NET Framework component.
b. namespaces, development
417. Which namespace do the classes, allowing you to support COM+ functionality, are located? System.EnterpriseServices
418. What is a serviced component? A serviced component is a class that derives from the System.EnterpriseServices.ServicedComponent class, which is the base class for all classes that use COM+ component services. You create and register each service component before it can access the COM+ services.
419. Which class do you need to define when creating serviced components? To create a serviced component, you need to define a class that is derived directly from the ServicedComponent base class.
420. What is use of ContextUtil class? ContextUtil is the preferred class to use for obtaining COM+ context information.
421. How do you assign a name and ID to a COM+ application? The application ID serves as an index for all application searches made during the registration process. The application ID is assigned by using the ApplicationID attribute that is derived from the System.EnterpriseServices namespace.
c. usage, registering
422. How will you register com+ services? The .NET Framework SDK provides the .NET Framework Services Installation Tool (Regsvcs.exe - a command-line tool) to manually register an assembly containing serviced components. You can also access these registration features programmatically with the System.EnterpriseServices.RegistrationHelper class by creating an instance of class RegistrationHelper and using the method InstallAssembly
423. What is the importance of the activation type attribute in the registration of a serviced component? You use the activation type attribute to specify whether the created serviced component is created in the library of the caller process or in a new process of the server.
424. Is it true that COM objects no longer need to be registered on the server? Yes and No. Legacy COM objects still need to be registered on the server before they can be used. COM developed using the new .NET Framework will not need to be registered. Developers will be able to auto-register these objects just by placing them in the 'bin' folder of the application.
d. Interop, COM objects, wrappers
425. Interop Services? The InteropServices (System.Runtime.Interop) namespace provides a collection of classes useful for accessing COM objects, and native APIs from .NET. The types in the InteropServices namespace fall into the following areas of functionality: attributes, exceptions, managed definitions of COM types, wrappers, type converters, and the Marshal class. The common language runtime provides two mechanisms for interoperating with unmanaged code: Platform invoke, which enables managed code to call functions exported from an unmanaged library. COM interop, which enables managed code to interact with COM objects through interfaces. Both platform invoke and COM interop use interop marshaling to accurately move method arguments between caller and callee and back, if required.
426. What is RCW (Run time Callable Wrappers)? The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.
427. So can a COM object talk to a .NET object? Yes, through Runtime Callable Wrapper (RCW) or PInvoke.
428. What is Pinvoke? Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic-link libraries (DLLs), such as those in the Win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed.
429. How do you generate an RCW from a COM object? Use the Type Library Import utility shipped with SDK. tlbimp COMobject.dll /out:.NETobject.dll or reference the COM library from Visual Studio in your project.
430. How do you make a NET component talk to a COM component? To enable the communication between COM and .NET components, the .NET Framework generates a COM Callable Wrapper (CCW). The CCW enables communication between the calling COM code and the managed code. It also handles conversion between the data types, as well as other messages between the COM types and the .NET types.
431. What are the two special steps you need to take to ensure that a COM component can use a component from a .NET assembly? You must register the .NET assembly in the system registry using RegAsm.exe. You must make sure that the COM component can find the .NET assembly, either by placing the .NET assembly in the global assembly cache, by placing the two components in the same folder, or by following the other assembly-probing rules.
432. What is CCW (COM Callable Wrapper)? A proxy object generated by the common language runtime so that existing COM applications can use managed classes, including .NET Framework classes, transparently.
433. How does you handle this COM components developed in other programming languages in .NET? Using RCW(Runtime Callable wrapper) with help of tlbimp – utility.
434. I can’t import the COM object that I have on my machine. Did you write that object? You can only import your own objects. If you need to use a COM component from another developer, you should obtain a Primary Interop Assembly (PIA) from whoever authored the original object.
435. I want to expose my .NET objects to COM objects. Is that possible? Yes, but few things should be considered first. Classes should implement interfaces explicitly. Managed types must be public. Methods, properties, fields, and events that are exposed to COM must be public. Types must have a public default constructor with no arguments to be activated from COM. Types cannot be abstract.
436. Can you inherit a COM class in a .NET application? The .NET Framework extends the COM model for reusability by adding implementation inheritance. Managed types can derive directly or indirectly from a COM coclass; more specifically, they can derive from the runtime callable wrapper generated by the runtime. The derived type can expose all the method and properties of the COM object as well as methods and properties implemented in managed code. The resulting object is partly implemented in managed code and partly implemented in unmanaged code.
437. Suppose I call a COM object from a .NET application, but COM object throws an error. What happens on the .NET end? COM methods report errors by returning HRESULTs; .NET methods report them by throwing exceptions. The runtime handles the transition between the two. Each exception class in the .NET Framework maps to an HRESULT.
438. How CCW and RCW is working?
11. .NET Remoting objects
a. general
439. What is Remoting? 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.
440. Flow of remoting?
441. What’s a Windows process? It’s an application that’s running and had been allocated memory.
442. What’s typical about a Windows process in regards to memory allocation? Each process is allocated its own block of available RAM space, no process can access another process’ code or data. If the process crashes, it dies alone without taking the entire OS or a bunch of other applications down.
443. Why do you call it a process? What’s different between process and application in .NET, not common computer usage, terminology? A process is an instance of a running application. An application is an executable on the hard drive or network. There can be numerous processes launched of the same application (5 copies of Word running), but 1 process can run just 1 application.
444. What distributed process frameworks outside .NET do you know? Distributed Computing Environment/Remote Procedure Calls (DEC/RPC), Microsoft Distributed Component Object Model (DCOM), Common Object Request Broker Architecture (CORBA), and Java Remote Method Invocation (RMI).
445. What’s a proxy of the server object in .NET Remoting? It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.
446. What are remotable objects in .NET Remoting? Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.
447. Describe the two types of remotable objects. The two types of remotable objects are a) Marshal-by-value objects. These objects are copied and passed by value out of the application domain. b) Marshal-by-reference objects. The clients that use these objects need a proxy to access the object remotely.
448. Describe the two types of activation modes of the .NET Remoting system. The two types of activation modes in the .NET Remoting system are. a) Server activation. In server activation, objects are created on the server when you call a method in the server class. However, objects are not created when you use the new keyword to create an instance of the server class. b) Client activation. In client activation, objects are created on the server when you create an instance using the new keyword.
449. CAO and SAO. 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)
450. 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.
451. What are channels in .NET Remoting? Channels represent the objects that transfer the other serialized objects from one application domain to another and from one computer to another, as well as one process to another on the same box. A channel must exist before an object can be transferred.
452. What is Application Domain? The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries.
453. How does an AppDomain get created? AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.
using System;
using System.Runtime.Remoting;
public class CAppDomainInfo : MarshalByRefObject {
        public string GetAppDomainInfo() {
                return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
        }
}
public class App {
        public static int Main() {
                AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );
                ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );
                CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());
                string info = adInfo.GetAppDomainInfo();
                Console.WriteLine( "AppDomain info: " + info );
                return 0;
        }
}
b. namespaces, development
454. What are possible implementations of distributed applications in .NET? .NET Remoting and ASP.NET Web Services. If we talk about the Framework Class Library, noteworthy classes are in System.Runtime.Remoting and System.Web.Services.
455. When would you use .NET Remoting and when Web services? Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.
456. Why do you use delegates in your remoting applications? You use delegates to implement callback functions, event programming, and asynchronous programming in your remoting applications. Events use delegates to enable callback functions to the client in remoting applications. This enables the client and the remote application to function as domain servers. Therefore, you need to design a server/server application instead of designing a client/server application.
457. What steps do you perform to implement asynchronous programming in a remoting application? The steps to implement asynchronous programming in a remoting application are: a) Create an instance of an object that can receive a remote call to a method, b) Wrap that instance method with an AsyncDelegate method, c) Wrap the remote method with another delegate, d) Call the BeginInvoke method on the second delegate, passing any arguments, the AsyncDelegate method, and some object to hold the state, e) Wait for the server object to call your callback method.
458. Serialize and MarshalByRef?
459. What is serialization in .NET? What are the ways to control serialization? 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).Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialized, an exact clone of the original object is created. Binary serialization preserves type fidelity, which is useful for preserving the state of an object between different invocations of an application. For example, you can share an object between different applications by serializing it to the clipboard. You can serialize an object to a stream, disk, memory, over the network, and so forth. Remoting uses serialization to pass objects "by value" from one computer or application domain to another.XML serialization serializes only public properties and fields and does not preserve type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is an open standard, which makes it an attractive choice. 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.
460. Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.
461. Write syntax to serialize class using XML Serializer?

462. What is a formatter? A formatter is an object that is responsible for encoding and serializing data into messages on one end, and deserializing and decoding messages into data on the other end.
463. Choosing between HTTP and TCP for protocols and Binary and SOAP for formatters, what are the trade-offs? Binary over TCP is the most efficient, SOAP over HTTP is the most interoperable.
464. What are the different formatters can be used in both? Why?.. binary/soap
465. What’s SingleCall activation mode used for? If the server object is instantiated for responding to just one single request, the request should be made in SingleCall mode.
466. What’s Singleton activation mode? A single object is instantiated regardless of the number of clients accessing it. Lifetime of this object is determined by lifetime lease.
467. How do you define the lease of the object? By implementing ILease interface when writing the class code.
468. How can you renew lifetime leases of objects? You can renew the lifetime lease of an object in the following two ways: a) A client application calls the ILease.Renew method. b) A sponsor renews the lease.
c. usage
469. What information do you need to provide to the .NET Remoting system to configure remote objects? You must provide the .NET Remoting system with the following information to configure remote objects: a) The activation type for the remote object, b) The channels that the remote object will use to receive messages from clients, c) The URL of the remote object, d) The type metadata that describes the type of your remote object
470. What security measures exist for .NET Remoting in System.Runtime.Remoting? None. Security should be taken care of at the application level. Cryptography and other security techniques can be applied at application or server level.
471. Can you configure a .NET Remoting object via XML file? Yes, via machine.config and application level .config file (or web.config in ASP.NET). Application-level XML settings take precedence over machine.config.
472. How can you automatically generate interface for the remotable object in .NET with Microsoft tools? Use the Soapsuds tool.
473. Can you pass SOAP messages through remoting?

12. XML Web Services
a. general
474. What is an XML Web service? XML Web services are program components that allow you to build scalable, loosely coupled, platform-independent applications. XML Web services enable disparate applications to exchange messages using standard protocols such as HTTP, XML, XSD, SOAP, and Web Services Description Language (WSDL).
475. What is a WebService and what is the underlying protocol used in it? Why Web Services? 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. a. 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. b. 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. c. 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
476. Difference between web services & remoting?
        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.             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.
477. Are Web Services a replacement for other distributed computing platforms? No. Web Services is just a new way of looking at existing implementation platforms.
478. What are the components of the XML Web service infrastructure? The components of the XML Web service infrastructure include XML Web services directories, XML Web services discovery, XML Web services description, and XML Web service wire formats.
479. What is the transport protocol you use to call a Web service? SOAP. Transport Protocols: It is essential for the acceptance of Web Services that they are based on established Internet infrastructure. This in fact imposes the usage of of the HTTP, SMTP and FTP protocols based on the TCP/IP family of transports. Messaging Protocol: The format of messages exchanged between Web Services clients and Web Services should be vendor neutral and should not carry details about the technology used to implement the service. Also, the message format should allow for extensions and different bindings to specific transport protocols. SOAP and ebXML Transport are specifications which fulfill these requirements. We expect that the W3C XML Protocol Working Group defines a successor standard.
480. True or False: A Web service can only be written in .NET? False (J2EE)^K481. What does WSDL stand for? Web Services Description Language
482. Where on the Internet would you look for Web services? UDDI repositories like uddi.microsoft.com, IBM UDDI node, UDDI Registries in Google Directory, enthusiast sites like XMethods.net.
483. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component? 1) When to Use Web Services: a) Communicating through a Firewall. When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option. b) Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors. c) Business-to-Business Integration This is an enabler for B2B integration which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically. d) Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary component-based reuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcomes this limitation. A scenario could be when you are building an app that aggregates the functionality of several other Applications. Each of these functions could be performed by individual apps, but there is value in perhaps combining the multiple apps to present a unified view in a Portal or Intranet. 2) When not to use Web Services: a) Single machine Applications. When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Components as there is very little overhead.  b) Homogeneous Applications on a LAN. If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps.
484. How does SOAP transport happen and what is the role of HTTP in it? How you can access a webservice using soap?
c. methods
485. What is code-behind? Code-behind allows you to associate Web Service source code written in a CLR compliant language (such as C# or VB.NET) as compiled in a separate file (typically *.asmx.cs or *.asmx.vb). You would otherwise typically find the executable code directly inserted into the .asmx file
486. What is Asynchronous Web Services?
487. Explain how to use the Begin and End methods on a Web Service to make an asynchronous method call. Every public Web method on a Web Service can be called either synchronously or asynchronously. To make an asynchronous call to a Web method, you call the method named Begin<webmethod>, where <webmethod> is the name of the method. This method requires a delegate to an appropriate callback method and returns a value of IAsyncResult. This value is returned as a parameter in the callback method. To retrieve the data returned by the Web method, call End<webmethod>, supplying a reference to the IAsyncResult returned by Begin<webmethod>. This will allow you to retrieve the actual data returned by the Web method.
488. Which attribute is used to create a Web method? You use the [WebMethod] attribute to declare a Web method that exposes the functionality of the XML Web service.
489. Can two different programming languages be mixed in a single ASMX file? No
490. What namespaces are imported by default in ASMX files? The following namespaces are imported by default. Other namespaces must be imported manually. System, System.Collections, System.ComponentModel, System.Data,
System.Diagnostics, System.Web, System.Web.Services
491. What’s the attribute for webservice method? What is the namespace for creating webservice? [WebMethod]
using System.Web;^Kusing System.Web.Services;
492. Which property of the WebMethod attribute allows you to maintain the state of objects across sessions in a Web method? The EnableSession property of the WebMethod attribute allows you to enable session state for a Web method.
493. What steps do you need to perform to enable transactions in a Web method? To enable transactions in a Web method, you need to perform the following steps: a) Add a reference to the System.EnterpriseServices.dll by using the Solution Explorer, b) Include the System.EnterpriseServices namespace in the XML Web service project, c) Set the TransactionOption property to an appropriate value.
494. When should you use asynchronous programming? You should use asynchronous programming when your application calls a method on an object that takes significant time to execute and you do not want the program to wait for the method to return.
495. Explain how you implement asynchronous programming using callbacks. A client calls the Begin method on the server object and passes a reference to the callback method. When the asynchronous method finishes execution, the server object calls the callback method on the client object. The callback method in turn calls the End method on the server object. The End method returns a value to the client.
496. Which method do you call for the first time when you access an XML Web service or service method with which the SOAP extension is configured to execute? You call the GetInitializer method the first time when you access an XML Web service or service method with which the SOAP extension is configured to execute.
497. In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice? WebService will support only DataSet.
498. What asynchronous web service means?
499. What are the events fired when web service called?

500. How will do transaction in Web Services?

d. debugging, testing
501. What are the different approaches to testing? There are two different approaches to testing: the waterfall approach and the evolutionary approach.
502. Explain the waterfall approach. The waterfall approach is a traditional approach in which each developer in the development team works in phases. These phases cover requirement analysis, design and specifications requirements, coding, final testing, and release.
503. Explain the evolutionary approach. In the evolutionary approach, you develop a modular piece or unit of application, test it, fix it, and then add another small piece that adds functionality. You then test the two units as an integrated component, increasing the complexity as you proceed.
504. True or False: To test a Web service you must create a windows application or Web application to consume this service? False
505. Which file contains configuration information, such as debug mode? The Web.config file contains configuration information, such as the debug mode and the authentication mode for a Web project. It also includes information about whether to display custom errors for a Web project.
506. Which file allows you to handle application-level events? The Global.asax file enables you to manage application-level events. This file resides in the root directory of an ASP.NET Web application or ASP.NET Web service. The Global.asax.cs or Global.asax.vb class file is a hidden, dependent file of Global.asax, which contains the code for handling application events such as the Application_OnError event.
507. Which element in the Web.config file do you use to manage custom error messages? You use the <customErrors/> element to manage custom error messages. You can set the <customErrors> mode attribute to On or RemoteOnly to enable custom error messages, and Off to disable the error messages.
508. What is the use of trace utility? 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. a. On the server, open the Web Services Description Language (WSDL) file. b. In the WSDL file, locate the <soap:address> element that corresponds to the service and change the location attribute for this element to port 8080. For example, if the location attribute specifies <http://MyServer/VDir/Service.wsdl> change this attribute to <http://MyServer:8080/VDir/Service.wsdl>. c. Run MSSOAPT.exe. d. 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). e. 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. a. Copy the WSDL file from the server to the client. b. Modify location attribute of the <soap:address> 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 <http://MyServer/VDir/Service.wsdl>, change it to <http://localhost:8080/VDir/Service.wsdl> and make note of "MyServer". c. On the client, run MSSOPT.exe. d. 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). e. In the Destination host box, enter the host specified in Step 2. f. In the Destination port box, enter the port specified in Step 2. g. Click OK.
e. deployment
509. What are the steps to deploy a Web service? Follow these steps to deploy a Web service: a) Copy the files for your XML Web service application to the Inetpub\Wwwroot folder, b) Open Internet Services Manager from the Administrative Tools folder, c) Expand the Default Web Site node, d) Right-click the Web service folder you copied to the Inetpub\Wwwroot folder to open its properties dialog box, e) Click Create in the properties dialog box to configure the virtual folder as the root of your Web application.
510. What type of Setup project do you create to deploy XML Web services? To deploy XML Web services, you create a Web Setup project.
511. What are the components that are published when you deploy a Web service? The components that are published when you deploy a Web service are a) The Web application directory, b) The <WebService>.asmx file, c) The <WebService>.disco file, d) The Web.config file, e) The \Bin directory
512. What is disco file? What does the .disco file contain? A .disco file contains links to other resources that describe your XML Web service and enables clients to discover an XML Web service. The discovery document contains information regarding other XML Web services that reside on the same or a different Web server.
513. What are the steps to configure discovery information for an XML Web service? To configure discovery information for an XML Web service, perform the following tasks: a) Create an XML document and insert the <?xml version="1.0" ?> tag in the first line, b) Add a <discovery> element, c) Add references to service descriptions, XSD schemas, and other discovery documents within the <discovery> element, d) Deploy the discovery document to a Web server.
514. What tasks do you need to perform to consume a Web service in a client application? To consume a Web service from a client application, you need to perform the following tasks: a) Add a Web reference to the XML Web service in the client application by discovering the XML Web service you want to consume, b) Generate a proxy class for the XML Web service, c) Create an object of the XML Web service proxy class in the client application, d) Access the XML Web service by using the proxy object.
515. Which tool do you need to use to compile the .resources files into satellite assemblies? Once you have created .resources files, you can compile them into satellite assemblies by using Al.exe, the Assembly Linker (AL) tool. The AL tool creates satellite assemblies from the .resources files that you specify. As you know, satellite assemblies cannot contain any executable code and can contain only resources. The following command shows you how to use the Al.exe tool to generate a satellite assembly:
al /t:lib /embed:myResource.resources /culture:de /out:MyRes.resources.dll
516. Where would you look for information about available XML Web services? UDDI
517. 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? 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.
518. What is a proxy in web service? How do I use a proxy server when invoking a Web service? ^K519. How to generate proxy class other than .net app and wsdl tool? 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^K/username:username /password:password /domain:domain <url or path>
520. How will you expose/publish a webservice?

13. ADO,Net
a. general
521. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET? SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.
522. Advantage of ADO.Net? a) ADO.NET Does Not Depend On Continuously Live Connections, b) Database Interactions Are Performed Using Data Commands, c) Data Can Be Cached in Datasets, d) Datasets Are Independent of Data Sources , e) Data Is Persisted as XML, f) Schemas Define Data Structures
523. Difference between OLEDB Provider and SqlClient ? 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.
524. 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. 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.
525. What are the major components of a Data Provider, and what function does each fulfill? An ADO.NET Data Provider is a suite of components designed to facilitate data access. Every Data Provider minimally includes a Connection object that provides the actual connection to the data source, a Command object that represents a direct command to the data source, a DataReader object that provides connected, forward-only, read-only access to a database, and a DataAdapter that facilitates disconnected data access.
526. What’s the data provider name to connect to Access database? Microsoft.Access.
527. How would u connect to database using .NET?
SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" + "Initial Catalog=northwind");^KnwindConn.Open();
528. What connections does Microsoft SQL Server support? Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).
529. Which one is trusted and which one is untrusted? Windows Authentication is trusted because the username and password are checked with the Active Directory, the SQL Server authentication is untrusted, since SQL Server is the only verifier participating in the transaction.
530. Why would you use untrusted verificaion? Web Services might use it, as well as non-Windows applications.
531. What does the parameter Initial Catalog define inside Connection String? The database name to connect to.
532. What are the options you need to specify when you set the ConnectionString property of a SqlConnection object? You need to specify the following options when you set the ConnectionString property of the SqlConnection object: Data Source, User ID, Password, Initial Catalog
533. What does Dispose method do with the connection object? Deletes it from the memory.
534. What is a pre-requisite for connection pooling? Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings.
535. What is the use of parameter object?
b. methods & classes ADO.Net
536. What’s the role of the DataReader class in ADO.NET connections? It returns a read-only dataset from the data source when the command is executed.
537. Which method do you invoke on the DataAdapter control to load your generated dataset with data? Fill()
538. Explain different methods and Properties of DataReader which you have used in your project?^KRead^KGetString^KGetInt32^Kwhile (myReader.Read())^K  Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));^KmyReader.Close();
539. How to check if a datareader is closed or opened? IsClosed()
540. What are good ADO.NET object(s) to replace the ADO Recordset object? DataSet.
541. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.  a) A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a dataset contains data from multiple database tables, it will typically contain multiple DataTable objects. That is, each DataTable object typically corresponds to a single database table or view. In this way, a dataset can mimic the structure of the underlying database. A dataset usually also contains relationships. A relationship within a dataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships. b) In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investor table for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object. For more information about cursor functionality, see Data Access Technologies. c) Minimized Open Connections: In ADO.NET you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the recordset can provide disconnected access, but ADO is designed primarily for connected access. There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio. d) Sharing Data Between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use a dataset, which can transmit an XML stream.  e) Richer data types.COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use. f) Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types. g) Penetrating Firewalls.A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.
542. Briefly contrast connected and disconnected data access in ADO.NET. In ADO.NET, connected data access is available through the DataReader, which is a lightweight class designed to provide very fast and efficient data access. It is severely limited, however, in that it can only provide forward-only data access, it does not allow editing, and it requires the exclusive use of a Connection object. In contrast, disconnected data access is facilitated by a DataAdapter, which manages the commands required for selecting and updating data. The DataAdapter executes a SELECT command against a database, opening a data connection just long enough to retrieve the data, and loads the data into a DataSet, which is an in-memory copy of the data. When the data is ready to be updated, the Data Provider manages the updates in the same way, generating the appropriate commands to update the database and keeping the connection open just long enough to execute those commands.
543. Difference between DataReader and DataAdapter / DataSet and DataAdapter? 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.^KSqlDataReader myReader = myCommand.ExecuteReader();^KYou use the Read method of the DataReader object to obtain a row from the results of the query.^Kwhile (myReader.Read())^K  Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));^KmyReader.Close();^KThe 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.
544. Briefly discuss the advantages and disadvantages of using typed DataSet objects. Typed DataSet objects allow you to work with data that is represented as members of the .NET common type system. This allows your applications to be aware of the types of data returned in a DataSet and serves to eliminate errors resulting from invalid casts, as any type mismatches are caught at compile time. Untyped DataSet objects, however, are useful if you do not know the structure of your data, and can be used with any data source.
545. How do you create relationships between two tables in a DataSet? You use the Add method of the Data Relation object to create a relationship between two tables in a DataSet. The Add method assumes a name for the relationship being created, and the DataColumn references the columns that you want to define as the parent and child columns in the relationship.
546. What are relation objects in dataset and how & where to use them? 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.^KcustDS.Relations.Add("CustOrders", custDS.Tables["Customers"].Columns["CustID"],^KcustDS.Tables["Orders"].Columns["CustID"]);^KOR^Kprivate void CreateRelation(){^K// Get the DataColumn objects from two DataTable objects in a DataSet.^K     DataColumn parentCol;^K  DataColumn childCol;^K// Code to get the DataSet not shown here.^K        parentCol = DataSet1.Tables["Customers"].Columns["CustID"];^K    childCol = DataSet1.Tables["Orders"].Columns["CustID"];^K// Create DataRelation.^K        DataRelation relCustOrder;^K     relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);^K// Add the relation to the DataSet.^K   DataSet1.Relations.Add(relCustOrder);^K}
547. Which method of the Command object is best suited for when you are using aggregate functions such as COUNT, MAX, and MIN in a SELECT statement? You use the ExecuteScalar method of the Command object when you are using aggregate functions in a SELECT statement because aggregate functions return one value.
548. What are the three possible settings for the CommandType property of a SqlCommand object or an OleDbCommand object, and what does each mean? A Command object can have a CommandType property setting of Text, StoredProcedure, or TableDirect. When set to Text, the command executes the SQL string that is stored in the Command object's CommandText property. When set to StoredProcedure, the command accesses a procedure stored on the database and returns the results. A CommandText setting of TableDirect indicates that the command should return the entire contents of the table indicated by the CommandText property.
549. How could you execute DDL commands, such as ALTER or CREATE TABLE, against a database with ADO.NET? You must use a Command object to execute DDL commands. You can set the CommandType property to Text and enter the appropriate DDL command in the CommandText property. Then call Command.ExecuteNonQuery to execute the command.
550. What events are exposed by the DataTable object? The events of the DataTable object are ColumnChanged, ColumnChanging, RowChanged, RowChanging, RowDeleted, and RowDeleting.
551. How to use a DataView to filter or sort data? You can apply sort criteria to a DataView by setting the Sort property to the name of a column or columns to be sorted by. The data represented in a DataView object can be filtered by setting the RowFilter property to a valid filter expression.
552. Explain the difference between handling transactions at the data set level and at the database level. Data sets provide implicit transactions, since changes to the data set aren' t made permanent in the database until you call the Update method. To handle transactions in a data set, process the Update method and check for errors. If errors occur during Update, none of the changes from the data set is made in the database. You can try to correct the error and resubmit the update, or you can roll back the changes to the data set using the RejectChanges method.
Databases provide explicit transactions through the Transaction object. You create a Transaction object from a database connection, and then assign that Transaction object to the commands you want to include in the transaction through the command object' s Transaction property. As you perform the commands on the database, you check for errors. If errors occur, you can either try to correct them and resubmit the command, or you can restore the state of the database using the Transaction object' s RollBack method. If no errors occur, you can make the changes permanent by calling the transaction object' s Commit method.
553. What are different transaction options?
554. How do u implement locking concept for dataset?
**
555. What happens when u try to update data in a dataset in .NET while the record is already deleted in SQL SERVER as backend? OR 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?)
**
556. 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?
**
557. How do you sort a dataset?
**
558. If a dataset contains 100 rows, how to fetch rows between 5 and 15 only?
**
559. Differences between dataset.clone and dataset.copy? 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.
c. data controls
560. Which method do you invoke on the DataAdapter control to load your generated dataset with data?  System.Data.Common.DataAdapter.Fill(System.Data.DataSet); If my DataAdapter is sqlDataAdapter and my DataSet is dsUsers then it is called this way: sqlDataAdapter.Fill(dsUsers);
561. How can you manage data currency on a form with several bound controls? Every data source on a form has an associated CurrencyManager object that keeps that of the "current" record with respect to bound controls. For convenience, all of the CurrencyManager objects represented on a form are exposed through the form's BindingContext property. The Position of the CurrencyManager can be changed, allowing navigation through the records.
d. data controls - Drop-down list
562. How do you display an editable drop-down list? Displaying a drop-down list requires a template column in the grid. Typically, the ItemTemplate contains a control such as a data-bound Label control to show the current value of a field in the record. You then add a drop-down list to the EditItemTemplate. In Visual Studio, you can add a template column in the Property builder for the grid, and then use standard template editing to remove the default TextBox control from the EditItemTemplate and drag a DropDownList control into it instead. Alternatively, you can add the template column in HTML view. After you have created the template column with the drop-down list in it, there are two tasks. The first is to populate the list. The second is to preselect the appropriate item in the list — for example, if a book’s genre is set to “fiction,” when the drop-down list displays, you often want “fiction” to be preselected.
e. data controls - Repeater
563. Can you edit data in the Repeater control? The Repeater has no built-in selection or editing support. The user may use the ItemCommand event to process control events that are raised from the templates to the control.
564. Which template must you provide, in order to display data in a Repeater control? ItemTemplate The Repeater control iterates over the bound data, rendering the ItemTemplate once for each item in the DataSource collection. It renders only the elements contained in its templates.
565. How can you provide an alternating color scheme in a Repeater control? AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties.
566. 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? You must set the DataMember property which Gets or sets the specific table in the DataSource to bind to the control and the DataBind method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query.
567. What tag do you use to add a hyperlink column to the DataGrid?
f. data controls - DataGrid
568. Describe the process of connecting DataGrid to database (table) through VStudio.Net.
1) In Server Explorer create Connection (MS driver Oracle)-> oracleClient.OracleConnection and OracleDataAdapter. Then drag and drop connection to the form. In oracleDataAdapter (rightClick-> context menu) => Generate DataSet (ok) -> dataSet11 - (rightClick-> menu)=> ViewSchema(ok)-> DataSet1.xsd file will appear.
2) Add DataGrid control -> DataGrid1. Properties: DataSource=dataSet11 + DataMember=EMP (table chosen).
3) Set columns -> DataGrid properties - Columns(collection). Not all -> uncheck Create Auto.. + add Columns manually.
4) add code to Page_Load event handler:
oracleDataAdapter1.Fill(dataSet11);
DataGrid1.DataBind();
5) run (F5) -> http://localhost/webApplication1/webForm1.aspx. That's all!
569. What’s the difference between the System.Web.UI.WebControls.DataGrid and and System.Windows.Forms.DataGrid? The Web UI control does not inherently support master-detail data structures. As with other Web server controls, it does not support two-way data binding. If you want to update data, you must write code to do this yourself. You can only edit one row at a time. It does not inherently support sorting, although it raises events you can handle in order to sort the grid contents. You can bind the Web Forms DataGrid to any object that supports the IEnumerable interface. The Web Forms DataGrid control supports paging. It is easy to customize the appearance and layout of the Web Forms DataGrid control as compared to the Windows Forms one.
570. Element DataGrid in .NET? How would you make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables? There are several ways to go about this task. The simplest way involves adding a single combobox to the DataGrid.Controls, and then selectively displaying it as needed when a combobox cell becomes the currentcell. All the work is done in a few event handlers and no overrides or derived classes are necessary. The other techniques require you to derive a columnstyle. Attached is a dropdown combobox sample (C#, VB) that shows how you can use a combobox in a datagrid. This implementation differs from other available columnstyle samples in that it derives from DataGridTextBoxColumn. These other samples derive directly from DataGridColumnStyle, and thus have to add functionality that already exists in DataGridTextBoxColumn.
571. If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why? No specifier!?
572. How do you customize the column content inside the datagrid? If you want to customize the content of a column, make the column a template column. Template columns work like item templates in the DataList or Repeater control, except that you are defining the layout of a column rather than a row.
573. How do you apply specific formatting to the data inside the cells? You cannot specify formatting for columns generated when the grid’s AutoGenerateColumns property is set to true, only for bound or template columns. To format, set the column’s DataFormatString property to a string-formatting expression suitable for the data type of the data you are formatting.
574. How do you hide the columns? One way to have columns appear dynamically is to create them at design time, and then to hide or show them as needed. You can do this by setting a column’s Visible property.
575. How do you check whether the row data has been changed? The definitive way to determine whether a row has been dirtied is to handle the changed event for the controls in a row. For example, if your grid row contains a TextBox control, you can respond to the control’s TextChanged event. Similarly, for check boxes, you can respond to a CheckedChanged event. In the handler for these events, you maintain a list of the rows to be updated. Generally, the best strategy is to track the primary keys of the affected rows. For example, you can maintain an ArrayList object that contains the primary keys of the rows to update.
576. How to implement DataGrid in .NET?
577. How would u make a combo-box appear in one column of a DataGrid?
578. What are the ways to show data grid inside a data grid for a master details type of tables?
579. If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why?
i. others
580. What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La. The wildcard character is %, the proper query with LIKE would involve ‘La%’.
581. Explain ACID rule of thumb for transactions. Transaction must be Atomic (it is one unit of work and does not dependent on previous and following transactions), Consistent (data is either committed or roll back, no “in-between” case where something has been updated and something hasn’t), Isolated (no transaction sees the intermediate results of the current transaction), Durable (the values persist if the data had been committed even if the system crashes right after).
582. Explain transaction atomicity. We must ensure that the entire transaction is either committed or rolled back.
583. Explain consistency. We must ensure that the system is always left at the correct state in case of the failure or success of a transaction.
584. Explain integrity. Ensure data integrity by protecting concurrent transactions from seeing or being adversely affected by each other’s partial and uncommitted results.
585. Explain durability. Make sure that the system can return to its original state in case of a failure.
14. Security in .Net (WinApps, Asp.Net, Webservices)
a. general - role-based security
586. What is Role-Based security? 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. **
587. Explain role-based security. In the role-based security model, access to parts of an application are granted or denied based on the role to which the callers belong. A role defines which members of a Windows domain are allowed to work with what components, methods, or interfaces.
588. You are creating a solution that must be accessed by members of a group called Developers and Administrators on the local machine. Describe a plan to implement this security scheme. Create one PrincipalPermission that represents the Developers group and another PrincipalPermission that represents the BUILTIN\Administrators group. Then, create a third permission that represents the union of the two by calling the Union method and demand that permission.
b. general - case access security
589. What is Code Access Security (CAS)? CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.
590. How does CAS work?  The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set.  For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)
591. Who defines the CAS code groups?  Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this:
Level = Machine
Code Groups:
1.  All code: Nothing
   1.1.  Zone - MyComputer: FullTrust
      1.1.1.  Honor SkipVerification requests: SkipVerification
   1.2.  Zone - Intranet: LocalIntranet
   1.3.  Zone - Internet: Internet
   1.4.  Zone - Untrusted: Nothing
   1.5.  Zone - Trusted: Internet
   1.6.  StrongName - 0024000004… Everything
Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent. ^K592. How do I define my own code group?  Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:
caspol -ag 1.3 -site www.mydomain.com FullTrust^KNow if you run caspol -lg you will see that the new group has been added as group 1.3.1: ^K   1.3.  Zone - Internet: Internet^K      1.3.1.  Site - www.mydomain.com: FullTrust^K...^KNote that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.^K593. How do I change the permission set for a code group?  Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this: ^Kcaspol -cg 1.2 FullTrust^KNote that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.
594. Can I create my own permission set? Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs.
- <Permission class="System.Security.Permissions.UIPermission, mscorlib, Ver=2000.14.1812.10, SN=03689116d3a4ae33" version="1">
  <Unrestricted />
  </Permission>
When you have edited the sample, add it to the range of available permission sets like this:^Kcaspol -ap samplepermset.xml^KThen, to apply the permission set to a code group, do something like this: ^Kcaspol -cg 1.3 SamplePermSet (By default, 1.3 is the 'Internet' code group)
595. I'm having some trouble with CAS. How can I diagnose my problem?  Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.
596. I can't be bothered with all this CAS stuff. Can I turn it off? Yes, as long as you are an administrator. Just run: caspol -s off
c. authentification methods
597. Name .NET authentification methods. ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods: 1) Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos). 2) Microsoft Passport authentication 3) Forms authentication 4) Client Certificate authentication
598. Which ASP.NET authentication mode is best suited to identifying and authorizing users who belong to a corporate network? Windows integrated authentication is best suited to authenticating users of a corporate network because it uses the accounts and permissions that already exist for network users.
599. How will you do windows authentication and what is the namespace? 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?
600. What is the difference between Windows and Forms authentication users lists in Web.config? Users lists for Windows authentication are included in the <authorization> element of Web.config. Users lists for Forms authentications are included in the <credentials> element of Web.config or as part of an external users database or file.
601. What are the different authentication modes in the .NET environment?
<authentication mode="Windows|Forms|Passport|None">
   <forms name="name"
          loginUrl="url"
          protection="All|None|Encryption|Validation"
          timeout="30" path="/" >
          requireSSL="true|false"
          slidingExpiration="true|false">
      <credentials passwordFormat="Clear|SHA1|MD5">
         <user name="username" password="password"/>
      </credentials>
   </forms>
   <passport redirectUrl="internal"/>
</authentication>
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.           602. Briefly highlight the differences between imperative and declarative security as they pertain to code access security. Imperative security is implemented by calling methods of Permission objects in code at run time. Declarative security is configured by attaching attributes representing permissions to classes and methods. Imperative security allows a finer control over the point in execution where permissions are demanded, but declarative security is emitted into metadata, and required permissions can be discovered through the classes in the System.Reflection namespace. Additionally, you can request assembly-wide permissions using the Assembly (assembly) directive with declarative security.
603. How do you require authentication using the Web.config file? Include the following <authorization> element to require authentication:
<authorization>
   <deny users="?" />
</authorization>
604. If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing) what would be the best approach to maintain login-in state for the users?

605. What is the main advantage of using Basic authentication instead of Digest authentication or Integrated Windows security? The main advantage of using Basic authentication is that it is part of the HTTP specification and it is supported by most browsers.
606. Which authentication methods, Basic, Digest, or Integrated Windows, required Active Directory? Digest.
607. Is Forms-based authentication or Microsoft Passport authentication based on cookies? Or both? Both.
608. How can you ensure that only authorized users access your Web service? You can use the <authorization> element to specify the users and roles that can access your Web service. This element enables you to implement both positive and negative authorization assertions. You can use this element to allow or deny access to your Web service based on specific users or roles.
d. authorization methods
609. What is the difference between authentication and authorization? Authentication: Accepts credentials from a user, Validates the credentials. Authorization: Given the authentication credentials supplied, determines the right to access a resource, Can be assigned by user name or by role.
610. Explain authorization levels in .net ?

e. ASP.Net
611. Security types in ASP/ASP.NET? Different Authentication modes?
612. How .Net has implemented security for web applications?
613. How to do Forms authentication in asp.net?
614. How you will protect / secure a web service? 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: a) Parse a SOAP request for valid values b) Authenticate access at the Web Method level (they can authenticate at the Web Service level) c) Stop reading a request as soon as it is recognized as invalid
f. Encryption
615. What is the namespace for encryption? System.Security.Cryptography.
b. SSL
616. How does the Secure Sockets Layer (SSL) provide security in a Web application? SSL protects data exchanged between a client and a Web application by encrypting the data before it is sent across the Internet.
617. How do you begin and end secure communication via SSL? To begin secure communication, specify the https protocol in an address. For example:
<a href="https://www.contoso.com/secure.htm">Secure page.</a>
To end secure communication, specify the http protocol. For example:
<a href="http://www.contoso.com/Default.htm">Not secure.</a>
15. Unmanaged code
618. What is the managed and unmanaged code in .net? The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime’s functionality and enable you to write code that benefits from this managed execution environment. Code that you develop with a language compiler that targets the runtime is called managed code; it benefits from features such as cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services.
619. Describe the advantages of writing a managed code application instead of unmanaged one. What’s involved in certain piece of code being managed? The advantages include automatic garbage collection, memory management, support for versioning and security. These advantages are provided through .NET FCL and CLR, while with the unmanaged code similar capabilities had to be implemented through third-party libraries or as a part of the application itself.
620. How do you call unmanaged methods from your .NET code through PInvoke? Supply a DllImport attribute. Declare the methods in your .NET code as static extern. Do not implement the methods as they are implemented in your unmanaged code, you’re just providing declarations for method signatures.
621. Can you retrieve complex data types like structs from the PInvoke calls? Yes, just make sure you re-declare that struct, so that managed code knows what to do with it.

Followers