Tuesday, May 22, 2007

ASP.NET

ASP.NET is the latest version of Microsoft's Active Server Pages technology (ASP).

What you should already know
Before you continue you should have a basic understanding of the following:
· WWW, HTML and the basics of building Web pages
· Scripting languages like JavaScript or VBScript
· The basics of server side scripting

What is ASP?
ASP is a server side scripting technology that enables scripts (embedded in web pages) to be executed by an Internet server.
· ASP is a Microsoft Technology
· ASP stands for Active Server Pages
· ASP is a program that runs inside IIS
· IIS stands for Internet Information Services
· IIS comes as a free component with Windows 2000
· IIS is also a part of the Windows NT 4.0 Option Pack
· The Option Pack can be downloaded from Microsoft
· PWS is a smaller - but fully functional - version of IIS
· PWS can be found on your Windows 95/98 CD

What is an ASP File?
· An ASP file is just the same as an HTML file
· An ASP file can contain text, HTML, XML, and scripts
· Scripts in an ASP file are executed on the server
· An ASP file has the file extension ".asp"

How Does it Work?
· When a browser requests an HTML file, the server returns the file
· When a browser requests an ASP file, IIS passes the request to the ASP engine on the server
· The ASP engine reads the file, line by line, and executes the scripts in the file
· Finally, the ASP file is returned to the browser as plain HTML

Before you study ASP .NET, it would help to have a basic understanding of Microsoft's ASP technology.

What is ASP+?
· ASP+ is the same as ASP.NET.
· ASP+ is just an early name used by Microsoft when they developed ASP.NET.

What is ASP.NET?
· ASP 3.0 is the latest version of ASP, but there will never be an ASP 4.0 version.
· ASP.NET is the next generation ASP, but it's not an upgraded version of ASP. ASP.NET is an entirely new paradigm for server-side ASP scripting.
· ASP.NET is a part of the .NET Framework. Microsoft spent three years rewriting ASP.NET from the ground up, and ASP.NET is not fully backward compatible with ASP 3.0.

.NET Framework
The .NET Framework is the infrastructure for the Microsoft .NET platform.
The .NET Framework is an environment for building, deploying, and running Web applications and Web Services.
The .NET Framework contains a common language runtime and common class libraries - like ADO.NET, ASP.NET and Windows Forms - to provide advanced standard services that can be integrated into a variety of computer systems.
The .NET Framework provides a feature-rich application environment, simplified development and easy integration between a number of different development languages.
The .NET Framework is language neutral. Currently it supports C++, C#, Visual Basic, and JScript (Microsoft's version of JavaScript).
Microsoft's Visual Studio.NET is a common development environment for the .NET Framework.


Differences between ASP and ASP .NET
ASP .NET has better language support, a large set of new controls and XML based components, and better user authentication.
ASP .NET provides increased performance by running compiled code.
ASP .NET code is not fully backward compatible with ASP.

New in ASP .NET
· Better language support
· Programmable controls
· Event-driven programming
· XML-based components
· User authentication, with accounts and roles
· Higher scalability
· Increased performance - Compiled code
· Easier configuration and deployment
· Not fully ASP compatible

Language Support
ASP .NET uses the new ADO .NET.
ASP .NET supports full Visual Basic, not VBScript.
ASP .NET supports C# (C sharp) and C++.
ASP .NET supports JScript as before.

ASP .NET Controls
ASP .NET contains a large set of HTML controls. Almost all HTML elements on a page can be defined as ASP .NET control objects that can be controlled by scripts.
ASP .NET also contains a new set of object oriented input controls, like programmable list boxes and validation controls.
A new data grid control supports sorting, data paging, and everything you expect from a dataset control.

Event Aware Controls
All ASP .NET objects on a Web page can expose events that can be processed by ASP .NET code.
Load, Click and Change events handled by code makes coding much simpler and much better organized.

ASP .NET Components
ASP .NET components are heavily based on XML. Like the new AD Rotator, that uses XML to store advertisement information and configuration.

User Authentication
ASP .NET supports forms-based user authentication, including cookie management and automatic redirecting of unauthorized logins.
(You can still do your custom login page and custom user checking).

User Accounts and Roles
ASP .NET allows for user accounts and roles, to give each user (with a given role) access to different server code and executables.

High Scalability
Much has been done with ASP .NET to provide greater scalability.
Server to server communication has been greatly enhanced, making it possible to scale an application over several servers. One example of this is the ability to run XML parsers, XSL transformations and even resource hungry session objects on other servers.

Compiled Code
The first request for an ASP .NET page on the server will compile the ASP .NET code and keep a cached copy in memory. The result of this is greatly increased performance.

Easy Configuration
Configuration of ASP .NET is done with plain text files.
Configuration files can be uploaded or changed while the application is running. No need to restart the server. No more metabase or registry puzzle.

Easy Deployment
No more server restart to deploy or replace compiled code. ASP .NET simply redirects all new requests to the new code.

Compatibility
ASP .NET is not fully compatible with earlier versions of ASP, so most of the old ASP code will need some changes to run under ASP .NET.
To overcome this problem, ASP .NET uses a new file extension ".aspx". This will make ASP .NET applications able to run side by side with standard ASP applications on the same server.


Installing ASP.NET
ASP.NET is easy to install. Just follow the instructions below.

What You Need
A Windows Computer
ASP.NET is a Microsoft technology. To run ASP.NET you need a computer capable of running Windows.

Windows 2000 or XP
If you are serious about developing ASP.NET applications you should install Windows 2000 Professional or Windows XP Professional.
In both cases, make sure you install the Internet Information Services (IIS) from the Add/Remove Windows components dialog.

Service Packs and Updates
Before ASP.NET can be installed on your computer, it is necessary to have all relevant service packs and security updates installed.
The easiest way to do this is to activate your Windows Internet Update. When you access the Windows Update page, you will be instructed to install the latest service packs and all critical security updates. For Windows 2000, make sure you install Service Pack 2. I will also recommend that you install Internet Explorer 6.
Read the note about connection speed and download time at the bottom of this page.

Remove Your Beta Version
If you have a Beta version of ASP.NET installed, we recommend that you completely uninstall it. Or even better: start with a fresh Windows 2000 or XP installation.
Install .NET
From your Windows Update you can now select to install the Microsoft .NET Framework.
After download, the .NET framework will install itself on your computer - there are no options to select for installation.
You should now be ready to develop your first ASP.NET application!

The .NET Software Development Kit
If you have the necessary bandwidth to download over 130 MB, you might consider downloading the full Microsoft .NET Software Development Kit (SDK).
We fully recommend getting the SDK for learning more about .NET and for the documentation, samples, and tools included.

Connection Speed and Download Time
If you have a slow Internet connection, you might have problems downloading large files like the service packs, the SDK and the latest version of Internet Explorer.
If download speed is a problem, our best suggestion is to get the latest files from someone else, from a colleague, from a friend, or from one of the CDs that comes with many popular computer magazines. Look for Windows 2000 Service Pack 2, Internet Explorer 6, and the Microsoft .NET Framework.

Monday, May 21, 2007

ADO.NET

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

How would u connect to database using .NET?
SqlConnection nwindConn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI;" + "Initial Catalog=northwind");nwindConn.Open();

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
.custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustID"],
custDS.Tables["Orders"].Columns["CustID"]);
OR
private void CreateRelation()
{
// Get the DataColumn objects from two DataTable objects in a DataSet
.DataColumn parentCol;
DataColumn childCol;
// Code to get the DataSet not shown here
.parentCol = DataSet1.Tables["Customers"].Columns["CustID"];childCol = DataSet1.Tables["Orders"].Columns["CustID"];
// Create DataRelation
.DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol);
// Add the relation to the DataSet
.DataSet1.Relations.Add(relCustOrder);}

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.

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

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
.SqlDataReader myReader = myCommand.ExecuteReader();
You use the Read method of the DataReader object to obtain a row from the results of the query.
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();
The DataSet is a memory-resident representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple and differing data sources, used with XML data, or used to manage data local to the application. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.
The DataAdapter serves as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by mapping Fill, which changes the data in the DataSet to match the data in the data source, and Update, which changes the data in the data source to match the data in the DataSet. If you are connecting to a Microsoft SQL Server database, you can increase overall performance by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection objects.

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

Explain different methods and Properties of DataReader which you have used in your project?Read
GetString
GetInt32
while (myReader.Read())
Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();

What happens when we issue Dataset.ReadXml command?
Reads XML schema and data into the DataSet.

In how many ways we can retrieve table records count? How to find the count of records in a dataset?
foreach(DataTable thisTable in myDataSet.Tables){
// For each row, print the values of each column.
foreach(DataRow myRow in thisTable.Rows){

How to check if a datareader is closed or opened?
IsClosed()

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?)**

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?**

How do you sort a dataset?**

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

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.

What is the use of parameter object?**

How to generate XML from a dataset and vice versa?**

What is method to get XML and schema from Dataset?
getXML () and get Schema ()

How do u implement locking concept for dataset?**

C# Language Features

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)

What is Polymorphism? How does VB.NET/C# achieve polymorphism?**
class Token
{
public string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public new string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
For the above code What is the "new" keyword and Which Class Method is called here
It will call base class Display method

class Token
{
public virtual string Display()
{
//Implementation goes here
return "base";
}
}
class IdentifierToken:Token
{
public override string Display() //What is the use of new keyword
{
//Implementation goes here
return "derive";
}
}
static void Method(Token t)
{
Console.Write(t.Display());
}
public static void Main()
{
IdentifierToken Variable=new IdentifierToken();
Method(Variable); //Which Class Method is called here
Console.ReadLine();
}
Derive

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.



Interfaces vs. Abstract Classes
Feature --> Interface --> Abstract class
Multiple inheritance
1. A class may implement several interfaces.
2. A class may extend only one abstract class.

Default implementation
1. An interface cannot provide any code at all, much less default code.
2. An abstract class can provide complete code, default code, and/or just stubs that have to be overridden.

Constants
1. Static final constants only, can use them without qualification in classes that implement the interface. On the other paw, these unqualified names pollute the namespace. You can use them and it is not obvious where they are coming from since the qualification is optional.
2. Both instance and static constants are possible. Both static and instance intialiser code are also possible to compute the constants.

Third party convenience
1. An interface implementation may be added to any existing third party class.
2. A third party class must be rewritten to extend only from the abstract class.

is-a vs -able or can-do
1. Interfaces are often used to describe the peripheral abilities of a class, not its central identity, e.g. an Automobile class might implement the Recyclable interface, which could apply to many otherwise totally unrelated objects.
2. An abstract class defines the core identity of its descendants. If you defined a Dog abstract class then Damamation descendants are Dogs, they are not merely dogable. Implemented interfaces enumerate the general things a class can do, not the things a class is.

Plug-in
1. You can write a new replacement module for an interface that contains not one stick of code in common with the existing implementations. When you implement the interface, you start from scratch without any default implementation. You have to obtain your tools from other classes; nothing comes with the interface other than a few constants. This gives you freedom to implement a radically different internal design.
2. You must use the abstract class as-is for the code base, with all its attendant baggage, good or bad. The abstract class author has imposed structure on you. Depending on the cleverness of the author of the abstract class, this may be good or bad. Another issue that's important is what I call "heterogeneous vs. homogeneous." If implementors/subclasses are homogeneous, tend towards an abstract base class. If they are heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this context.) If the various objects are all of-a-kind, and share a common state and behavior, then tend towards a common base class. If all they share is a set of method signatures, then tend towards an interface.

Homogeneity
1. If all the various implementations share is the method signatures, then an interface works best.
2. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best.

Maintenance
1. If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method.
2. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.

Speed
1. Slow, requires extra indirection to find the corresponding method in the actual class. Modern JVMs are discovering ways to reduce this speed penalty.
2. Fast

Terseness
1. The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all presumed so.
2. You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.

Adding functionality
1. If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.
2. If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

Write one code example for compile time binding and one for run time binding? What is early/late binding?
An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes.' Create a variable to hold a new object.Dim FS As FileStream' Assign a new object to the variable.FS = New FileStream("C:\tmp.txt", FileMode.Open)By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects.Dim xlApp As ObjectxlApp = CreateObject("Excel.Application")

Can you explain what inheritance is and an example of when you might use it?

How can you write a class to restrict that only one object of this class can be created (Singleton class)?

Constructor/Destructor

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.

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:- You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method.- You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

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)

Overloaded constructor will call default constructor internally?(no)

What are virtual destructors?

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:
1. Destructors are invoked automatically, and cannot be invoked explicitly.
2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor.
3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it.
4. Destructors cannot be used with structs. They are only used with classes.
5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance.
6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction.
7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived.http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconfinalizemethodscdestructors.asp

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.

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

What is boxing & unboxing?

What is check/uncheck?

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

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


try
{...}
catch
{...//exception occurred here. What'll happen?}
finally{..}
It will throw exception.

What will do to avoid prior case?try
{
try
{
...
}
catch
{
...
//exception occurred here.
}
finally
{
...
}
}
catch
{
...
}
finally
{
...
}
try
{
...
}
catch
{
...
}
finally
{
..
}

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.

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.

What’s different about switch statements in 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.
case 1:cost += 25;break;case 2:cost += 25;goto case 1;

Access Specifiers

What are the access-specifiers available in c#?
Private, Protected, Public, Internal, Protected Internal.

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.

OOPS

What are the OOPS concepts?
· 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.
· 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.
· 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.

What is the difference between a Struct and a Class?
· 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.

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

What is Inheritance, Multiple Inheritance, Shared and Repeatable Inheritance?**

What is Method overloading?
Method overloading occurs when a class contains two methods with the same name, but different signatures.

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.

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.

You have one base class virtual function how will call that function from derived class?
class a
{
public virtual int m()
{
return 1;
}
}
class b:a
{
public int j()
{
return m();
}
}

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.

COM

Interop Services?
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.

How does u handle this COM components developed in other programming languages in .NET?
What is RCW (Runtime 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.

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.

How CCW and RCW is working?**

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.EnterpriseServicesRegistrationHelper class by creating an instance of class RegistrationHelper and using the method InstallAssembly.

What is use of ContextUtil class?
ContextUtil is the preferred class to use for obtaining COM+ context information.

What is the new three features of COM+ services, which are not there in COM (MTS)?**

Is the COM architecture same as .Net architecture? What is the difference between them?**

Can we copy a COM dll to GAC folder?**

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.

Is it true that COM objects no longer need to be registered on the server?
Answer: 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.
Can .NET Framework components use the features of Component Services?Answer: Yes, you can use the features and functions of Component Services from a .NET Framework component. http://msdn.microsoft.com/library/techart/Pahlcompserv.htm

Jagged Arrays

What are Jagged Arrays?
A Jagged Array is an array of an array in which the length of each array index can differ.
Example: A Jagged Array can be used to create a table in which the lengths of the row are not same. This array is declared using square brackets ([ ]) to indicate each dimension.
The following code demonstrates the creation of a two-dimensional jagged array.Class Jagged{public static void Main(){int [][] jagged=new int [3][];jagged[0]=mew int[4]jagged[1]=mew int[3]jagged[2]=mew int[5]int I;‘Storing values in first arrayfor (I=0;I<4;I++)jagged[0][I]=I;‘Storing values in second array

for( I=0;I<3;I++)
jagged[1][I]=I;
‘Storing values in third array

for(I=0;I<5;I++)
jagged[2][I]=I;
‘Displaying values from first array

for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
‘Displaying values from second array

for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])

‘Displaying values from third array
for(I=0;I<5;I++)
Console.WriteLine(jagged[2][I])

}
}

Debugging and Error Handling

Different Types are Errors are:
· Fatal Errors à Errors that cause applications to fail completely
· Syntax Errors à Simple Errors in code that prevent compilation
· Semantic Errors (also known as Logic Errors) à Application logic is in some way flawed.

Debugging Methods available in VS
Debug builds maintain symbolic information about your application, so that VS is capable of knowing exactly what is happening as each line of code is executed. The symbolic information is contained in .pdb files, which you may have seen appearing in Debug directories on your computer. This enables you to perform many useful operations, which include:
· Outputting debugging information to VS
· Looking at the values of variables in scope during application execution
· Pausing and restarting program execution
· Automatically halting execution at certain points in the code
· Stepping through program execution a line at a time
· Monitoring changes in variable content during application execution
· Modifying variable content at runtime
· Performing test calls of functions

In the Output Window, you can see information relating to the compilation and execution of code, including errors encountered during compilation and so forth. This window has two modes: Build mode and Debug mode. These modes show you compilation and runtime information, respectively.

Debugging in Nonbreak (Normal) Mode
How do you output information to the Output Window at runtime?
Writing text to the Output window at runtime is very simple. You simply need to replace calls to Console.WriteLine() with the required call to write text where you want it. There are two commands you can use to do this:
· Debug.WriteLine() à this command works only for debug build. This won’t even be compiled into a release build. It will just disappear.
· Trace.WriteLine() à this command works for both the debug and release builds
Two versions of your application can be created from a single source file. The debug version displays all kinds of extra diagnostic information, whereas the release version won’t have this overhead.

Syntax for the general output of these functions is as follows:
:
This allows you to see at a glance what output messages are displayed in the Output window, which is useful for times when similar messages are output from different places in the application.

For Example:
Debug.WriteLine(“Added 1 to I”, “MyFunc”);
Result is:
MyFunc: Added 1 to i

Where does the Debug.WriteLine() and Trace.WriteLine() commands are present?
In the System.Diagnostics namespace.

What are the other commands that are equivalent to Console.Write() command?
· Debug.Write()
· Trace.Write()

And the other different Commands are as follows and they take the Boolean value parameters:
· Debug.WriteLineIf()
· Trace.WriteLineIf()
· Debug.WriteIf()
· Trace.WriteIf()

What command is used as an alternative to writing information to the Output window?
An alternative to writing information to the Output window is to use trace points. This is a feature of VS rather than C#, but serve the same function as using Debug.WriteLine(). They output debugging information without modifying your code.

What are the steps to add a trace point to the code?


Error-Handling techniques available in C#

Delegates

Define Delegates?
A delegate is a type that enables you to store references to functions. Delegates are declared much like functions, but with no function body and using the delegate keyword.

How is the delegate signature defined?
The delegate declaration specifies a function signature consisting of a return type and the parameter list. After defining a delegate, you can declare a variable with the type of that delegate. You can then initialize this variable as a reference to any function that has the same signature as that delegate.
Example:
delegate double ProcessDelegate(double param1, double param2);

static double Multiply(double param1, double param2)
{
return param1 * param2;
}

static double Divide(double param1, double param2)
{
return param1 / param2;
}

static void Main (string[ ] args)
{
ProcessDelegate process;
………………
if (input == “M”)
process = new ProcessDelegate(Multiply)
else
process = new ProcessDelegate(Divide
Console.WriteLine(“Result: {0}”, process(param1, param2));
Console.ReadKey();
)

Overloading Functions

Function overloading provides you with the ability to create multiple functions with the same name, but each working with different parameter types.
For Example:
Static int MaxValue (int[ ] intArray)
{
………………
return maxVal;
}

Static double MaxValue (double[ ] doubleArray)
{
………………
return maxVal;
}
Here both the function names MaxValue() is same but its signature is different. It would be error to define two functions with the same name and signature, but since these two functions have different signatures, this is fine.
The beauty of this type of code is that you don’t have to explicitly specify which of these two functions you wish to use. You simply provide an array parameter, and the correct function will be executed depending on the type of the parameter used.

All aspects of the function signature are included when overloading functions. For Example, you have two different functions that take parameters by value and by reference, respectively:
Static void ShowDouble (ref int val)
{
………………
}

Static void ShowDouble (int val)
{
………………
}
The choice as to which of these versions to use is based purely on whether the function call contains the ref keyword. The following would call the reference version:
ShowDouble (ref val);

And the following would call the value version:
ShowDouble (val);

Struct Functions

Structs are used for storing multiple data elements in one place. Also it has the ability to contain functions as well as data.
Struct Example:
Struct CustomerName
{
public string firstName, lastName;
}
You can use the struct in your code as follows:
CustomerName myCustomer;
myCustomer.firstName = “John”;
myCustomer.lastName = “Franklin”;
Console.WriteLine(“{0} {1}”, myCustomer.firstName, myCustomer.lastName);

Adding Functions to Structs:
By adding functions to structs, you can simplify this by centralizing the processing of common tasks such as follows:
Struct CustomerName
{
public string firstName, lastName;

public string Name()
{
return firstName + “” + lastName;
}
}
Now you can use the struct in your code as follows:
CustomerName myCustomer;
myCustomer.firstName = “John”;
myCustomer.lastName = “Franklin”;
Console.WriteLine( myCustomer.Name());

What is the difference between a struct and a class in C#?
The list of similarities between classes and structs is as follows:
· Longstructs can implement interfaces and can have the same kinds of members as classes.
Structs differ from classes in several important ways; however,
· structs are value types rather than reference types, and inheritance is not supported for structs.
· Struct values are stored on the stack or in-line.
· Careful programmers can sometimes enhance performance through judicious use of structs.
For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

The Main() Function

The Main() is the entry point for a C# application. When the execution is initiated, the Main() function executes and when the Main() function finishes the execution ends. There are four possible signatures you can use for the Main() function:
· Static void Main ()
· Static void Main (string[] args)
· Static int Main ()
· Static int Main (string[] args)
The args parameter of Main() is a method for accepting information from outside the application, specified at runtime. This information takes the form of command-line parameters. i.e. any command-line parameters that are specified are placed in this args array.

How do you add the command-line arguments?
The below method is the easiest way to add the arguments, rather than typing them at a command-line prompt every time.
· Right-click the project name in the Solution Explorer window and select Properties.
· Select the Debug page and add whatever command-line arguments you want to the Command Line Arguments setting
· Run the Application

Parameters and Return Values versus Global Data

Limitations on using the global variables are:
· The global data might be modified by code elsewhere in your application, which could cause unpredicted results
· There are times when you only ever want to use a function for one purpose, and using a global data store reduces the possibility that you will make an error in a function call, perhaps passing it with the wrong variable.

Variable Scope

A given variable is said to have a scope from where it is accessible.
· Local Variables
· Global Variables
Variables whose scope covers a single function are known as local variables.
Global Variables covers multiple functions. The variable is defined as follows:
Static string myString();
Note: For Global Variables, you must either use static or const keyword.

How do you refer to the global variable when you have the local and global variables with the same name in the program?
If you have both the local and global variables with the same name “myString”, you access the global variable in the program with the à Program.myString.

Note that the scope of variables also applies to those in branching and looping structures.
Note: The variable must be declared and initialized before use. Simply declaring a variable doesn’t do much. It is only when values are assigned to the variable then that values are allocated a place in memory to be stored. When the allocation takes place inside a loop, the value is defined as a local values and goes out of scope outside of the loop. Assigning a value outside of the loop ensures that the value is local to the main code, and it is still in scope inside the loop.

Out Parameter

What is an out parameter? What is the difference between ref and out parameters?
In addition to passing values by reference, you can also specify that a given parameter is an out parameter by using the out keyword, which is used in the same way as the ref keyword (as a modifier to the parameter in the function definition and in the function call.

What are the differences between ref and out parameters?
· It is illegal to use an unassigned variable as a ref parameter; you can use an unassigned variable as an out parameter.
· Out parameter must be treated as an unassigned value by the function that uses it. This means that it is OK to use the assigned variable as an out parameter, the value stored in this variable will be lost when the function executes.

Reference and Value Parameters

What is the Value Parameter? Explain with the example?
When used parameters that you have passed a value into a variable used by the function. Any changes made to this variable in the function have no effect on the parameter specified in the function call.
Example, consider a function that doubles and displays the value of a passed parameter:
Static void ShowDouble (int val)
{
val *= 2;
Console.WriteLine (“val doubled = {0}”, val);
}
Here the parameter, val, is doubled in this function. If you call it in the following way:
int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);
Result is:
myNumber = 5
val Double = 10
myNumber = 5
So here calling the ShowDouble() with myNumber as a parameter doesn’t affect the value of myNumber in Main(), even though the parameter it is assigned to, val is doubled.

What is the Reference Parameter? Explain with the example?
Passing the parameter by reference will help you to change the values of multiple variables. Any changes made to this variable will, therefore, be reflected in the value of the variable used as a parameter. To do this, you simply have to use the ref keyword to specify the parameter.
Example:
Static void ShowDouble ( ref int val)
{
val *= 2;
Console.WriteLine (“val doubled = {0}”, val);
}
Here the parameter, val, is doubled in this function. If you call it in the following way:
int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);
Result is:
myNumber = 5
val Double = 10
myNumber = 10
This time the myNumber has been modified by ShowDouble().

What are the limitations on the variable used as a ref parameter?
· Results in a change to the value of a reference parameter, so you must use a nonconstant variable in the function call. For example this is illegal:
Const int myNumber = 5;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);

· You must use an initialized variable. C#$ doesn’t allow you to assume that a ref parameter will be initialized in the function that uses it. The following code is illegal:
int myNumber;
Console.WriteLine (“myNumber = {0}”, myNumber);
ShowDouble(myNumber);
Console.WriteLine (“myNumber = {0}”, myNumber);

Functions

Define Functions?
Functions in C# are a means of providing blocks of code that can be executed at any point in an application.
· Functions have an advantage of making your code more readable.
· You can use this function from any point in your code, and use the same lines of code in each case. The function can be thought of as containing reusable code.
· Functions can also be used to create multipurpose code, allowing them to perform the same operation on varying data.
· You can supply a function with information to work in the form of parameters, and obtain results from functions in the form of return values. The parameters and return value of a function collectively define the signature of a function.
Example: you can supply an array to search as a parameter and obtain the maximum value in the array as a return value. This means that you can use the same function to work with a different array each time.

Function definition consists of the following:
· Two keywords, static and void
o Note: the void keyword is to indicate the function does not return a value
Example:
Static void Write()
{
……………
}
· Function name followed by parentheses, Ex: Write()
· A block of code to execute enclosed in curly braces
· Function names are usually written in PascalCasing.

When the Function returns a value, you have to modify the function in two ways:
· Specify the type of the return value in the function declaration instead of using the void keyword.
· Use the return keyword to the end of the function execution and transfer the return value to the calling code.
Example:
Static ()
{
……………
return ;
}

Example:
Static double GetVak()
{
return 3.2;
}
Note: The only limitation here is that must be a value that is either of type or can be implicitly converted to that type.

Note: The return values are usually the result of some processing carried out by the function. When the return statement is reached, program execution returns to the calling code immediately. No lines of code after this statement will be reached

Note: Placing return in a for loop, an if block, or any other structure causes the structure to terminate immediately and the function to terminate.

Note: The return statement is processed before reaching the closing } of the function.

When a Function is to accept the parameters, you must specify the following:
· A list of the parameters accepted by a function in its definition, along with the types of those parameters
· A matching list of parameters in each function call.
Example:
Static ( , …)
{
……………
return
}

Note: you can have any number of parameters, each with a type and a name. The parameters are separated using commas. Each of these parameters is accessible from code within the function as a variable.
Example:
Static double Product (double param1 double param2)
{
return param1 * param2
}

Parameter Matching:
When you call a function, you must match the parameters as specified in the function definition exactly. This means matching the parameter types, the number of parameters, and the order of the parameters.
Example:
Static coid MyFunction(string myString, double myDouble)
{
}
This function can’t be called as follows:
MyFunction (2.6, “Hello”);
You also can’t use as follows:
MyFunction (“Hello”);
Note: Here you are attempting to pass a double value as the first parameter and a string value as the second parameter, which is not the order in which the parameters are defined in the function definition.

Parameters Arrays:
C# allows you to specify one (and only one) special parameter for a function. This parameter is known as a parameter array. Parameter arrays allow you to call functions using a variable amount of parameters and are defined using the params keyword.
Parameter arrays can be a useful way to simplify your code, because you don’t have to pass arrays from your calling code. Instead, you pass several parameters of the same type that are placed in an array that you can use from within your function.
Example:
Static ( , ………., params [ ] )
{
…..
return ;
}
You can call the function using code like:
(, ………, , , ……)
Here , ,….. are values of type , which are used to initialize the array. The number of parameters that you specify here is almost limitless; the only restriction is that they are all of type . You can even specify no parameters at all.

Microsoft .NET Framework Questions

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.

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. The specification for the PE/COFF file formats is available at http://www.microsoft.com/whdc/hwdev/hardware/pecoffdown.mspx

What is Event - Delegate?
clear syntax for writing a event delegateThe event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code. The delegate can have one or more associated methods that will be called when your code indicates that the event has occurred. An event in one program can be made available to other programs that target the .NET Framework Common Language Runtime.
// keyword_delegate.cs// delegate declarationdelegate void MyDelegate(int i);
class Program
{
public static void Main()
{
TakesADelegate(new MyDelegate(DelegateFunction));
}
public static void TakesADelegate(MyDelegate SomeFunction)
{
SomeFunction(21);
}
public static void DelegateFunction(int i)
{
System.Console.WriteLine("Called by delegate with number: {0}.", i);
}
}

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.

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

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 syystem 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 - 0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: 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.

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 FullTrustNow if you run caspol -lg you will see that the new group has been added as group 1.3.1:
... 1.3. Zone - Internet: Internet
1.3.1. Site - www.mydomain.com: FullTrust...
Note 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.

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:
caspol -cg 1.2 FullTrustNote 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.

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. When you have edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet (By default, 1.3 is the 'Internet' code group)

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.

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 offhttp://www.codeproject.com/dotnet/UB_CAS_NET.asp

Which namespace is the base class for .net Class library?
system.object

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.

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.
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;
}
}

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

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.

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.

What is Custom attribute? How to create?
If I'm having custom attribute in an assembly, how to say that name in the code? The primary steps to properly design custom attribute classes are as follows:
· Applying the AttributeUsageAttribute ([AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)])
· Declaring the attribute. (class public class MyAttribute : System.Attribute { // . . . })
· Declaring constructors (public MyAttribute(bool myvalue) { this.myvalue = myvalue; })
· 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.
class MainClass {public static void Main(){System.Reflection.MemberInfo info = typeof(MyClass);object[] attributes = info.GetCustomAttributes();for (int i = 0; i < attributes.Length; i ++) {System.Console.WriteLine(attributes[i]);}}}

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.

How do you create threading in .NET? What is the namespace for that?**System.Threading.Thread

Serialize and MarshalByRef?
using directive vs using statementYou create an instance in a using statement to ensure that Dispose is called on the object when the using statement is exited. 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.The using directive has two uses:
· Create an alias for a namespace (a using alias).
· 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).

Describe the Managed Execution Process?The managed execution process includes the following steps:
· 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.
· Compiling your code to Microsoft intermediate language (MSIL). Compiling translates your source code into MSIL and generates the required metadata.
· 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.
· 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.

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:
· 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.
· 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.
· Perform "rich querying" on directory systems. ADSI technology allows for searching for an object by specifying two query dialects: SQL and LDAP.
· Access and use a single, hierarchical structure for administering and maintaining diverse and complicated network configurations by accessing an Active Directory tree.
· 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;

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:
· The garbage collector searches for managed objects that are referenced in managed code.
· The garbage collector attempts to finalize objects that are not referenced.
· The garbage collector frees objects that are not referenced and reclaims their memory.

Why do we need to call CG.SupressFinalize?
Requests that the system not call the finalizer method for the specified object. [C#]public static void SuppressFinalize(object obj);
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.

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

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.

What is the difference between CONST and READONLY?
Both are meant for constant values. 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.
readonly int b;public X(){b=1;}public X(string s){b=5;}public X(string s, int i){b=i;}
Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example:
public static readonly uint l1 = (uint) DateTime.Now.Ticks; (this can't be possible with const)

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.

What is the difference between Array and LinkedList?
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.

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

What are indexers?
Indexers are similar to properties, except that the get and set accessors of indexers take parameters, while property accessors do not.

What is Asynchronous call and how it can be implemented using delegates?

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

If you want to write your own dot net language, what steps you will u take care?

Describe the difference between inline and code behind - which is best in a loosely coupled solution?

How dot net compiled code will become platform independent?

Without modifying source code if we compile again, will it be generated MSIL again? C++ & C# differences**

More About Variables - Type Conversions and Complex Variable Types

What is Type Conversion?
Converting values from one type into another. Two forms of Type Conversions are:
· Implicit Conversions à where conversion from type A to type B is possible in all circumstances, and the rules for performing the conversions are simple enough for you to trust in the compiler.
· Explicit Conversions à where conversions from type A to type B is only possible in certain circumstances or where the rules for conversions are complicated enough to merit additional processing of some kind.

Explain Implicit Conversion?
Implicit Conversion requires no work on your part and no additional code.
For Ex: the values of ushort and char are effectively interchangeable, because both store a number between 0 and 65535. you can covert values between these types implicitly.
Ex2: the bool and string have no implicit conversions, but the numeric types have a few.

The following table shows the numeric conversions that the compiler can perform implicitly (Note: chars are stored as numbers, so char counts as a numeric type):
Type --> Can Safely Be Converted To
Byte - short, ushort, int, uint, long, ulong, float, double, decimal
Sbyte - short, int, long, float, double, decimal
Short - int, long, float, double, decimal
Ushort - int, uint, long, ulong, float, double, decimal
Int - long, float, double, decimal
Uint - long, ulong, float, double, decimal
Long - float, double, decimal
Ulong - float, double, decimal
Float - double
Char - ushort, int, uint, long, ulong, float, double, decimal

Implicit Conversion Rule is: any type A whose range of possible values completely fits inside the range of possible values of type B can be implicitly converted into that type. For Example, a short type variable is capable of storing values up to 32767, and the maximum value allowed into a byte is 255, so there could be problem if you try to convert a short value into a byte value.
However you can convert the short type variable to a byte type using an explicit conversion.

Explain Explicit Conversion?
Explicit conversions occur when you explicitly ask the compiler to convert a value from one data type to another. Because of this they require extra code, and the format of this code may vary, depending on the exact conversion method.

When you try to convert a short value into a byte, what is an error message the C# compiler throws?
Cannot implicitly convert type ‘short’ to ‘byte’. An explicit conversion exists (are you missing a cast?)
To get this code to compile, you need to add the code to perform an explicit conversion. The easiest way to do this is to cast the short variable into a byte.

What is casting?
Casting basically means forcing data from one type into another. The syntax is as follows:
(destinationType)variable.

What are the different Simple Numeric Types?
· byte, ubyte
· short, ushort
· int, uint
· long, ulong
· float
· double
· decimal

What are the different Simple Variable types?
· Char
· Bool
· String

What are the different Complex Variable types?
· Enumerations
· Structs
· Arrays

Flow Control

Boolean Logic:
The bool type can only hold either true or false value.
Boolean Comparison requires the use of Boolean operators (also known as relational operators).

The Relational Operators are as follows:
Operator --> Category --> Example Expression --> Result
== Binary Var1 = var2 == var3 Var1 is true if var2 = var3 or else var1 is false.
!= Binary Var1 = var2 != var3 Var1 is true if var2 is not equal to var3 or else var1 is false.
< var1 =" var2"> Binary Var1 = var2 > var3 Var1 is true if var2 is greater than var3 or else var1 is false.
<= Binary Var1 = var2 <= var3 Var1 is true if var2 is less than or equal to var3 or else var1 is false. >= Binary Var1 = var2 >= var3 Var1 is true if var2 is greater than or equal to var3 or else var1 is false.

Other Boolean Operators are:
Operator --> Category --> Example Expression --> Result
! Unary Var1 = ! var2 Var1 is true if var2 is false or else var2 is false. (Logical NOT)
& Binary Var1 = var2 & var3 Var1 is true if var2 and var3 both are either true. Otherwise var1 is false. (Logical AND)
Binary Var1 = var2 var3 Var1 is true if either var2 or var3 or both are true or else var1 is false. (Logical OR)
^ Binary Var1 = var2 ^ var3 Var1 is true if either var2 or var3, but not both, are true or else var1 is false. (Logical XOR or Exclusive OR).

Conditional Boolean Operators are:
Operator --> Category --> Example Expression --> Result
&&amp; Binary Var1 = var2 && var3 Var1 is true if var2 and var3 both are either true. Otherwise var1 is false. (Logical AND)
Binary Var1 = var2 var3 Var1 is true if either var2 or var3 or both are true or else var1 is false. (Logical OR)

Note: the results of operators && and are exactly the same as & and , but there is an important difference in the way this result is obtained, which can result in better performance.
Both of these operators (&&, ) first look at the value of their first operand (var2) and based on the value of this operand many not need to proceed to process the second operator (var3) at all. This isn’t the case for the & and operator. Because of this conditional evaluation of operands, you will see a small performance increase if you use && and operators instead of & or operators.

How will the conditional operators increase the performance?
For ex: if the value of the first operand of the && operator is false, then there is no need to consider the value of the second operand, because the result will be false regardless of the value of the second operand. Similarly, the operator will return true if its first operand is true, regardless of the value of the second operand.

Why do we still have the & and operator when the && and operators improve the performance?
These operators may be used to perform operations on numeric values. They operate on the series of bits stored in a variable rather than the value of the variable.

Bitwise Shift Operators are:
Operator --> Category --> Example Expression --> Result
>> Binary Var1 = var2 >> var3 Var1 is assigned the value obtained when the binary content of var2 is shifted var3 bits to the right.
<< var1 =" var2" var2 =" 10," var3 =" 2;" var1 =" var2" var1 =" 40" 101000 ="=""> Category --> Example Expression --> Result
&= Binary Var1 &= var2 Var1 is assigned the value that is the result of var1 & var2.
= Binary Var1 = var2 Var1 is assigned the value that is the result of var1 var2.
^= Binary Var1 ^= var2 Var1 is assigned the value that is the result of var1 ^ var2.
These work with both Boolean and numeric values in the same was as &, , and ^
Note: &= and = use the & and operators and not the && and operators

Bitwise Shift Assignment Operators are:
Operator --> Category --> Example Expression --> Result
>>= Unary Var1 >>= var2 Var1 is assigned the value obtained when the binary content of var1 is shifted var2 bits to the right.
<<= Unary Var1 <<= var2 Var1 is assigned the value obtained when the binary content of var1 is shifted var2 bits to the left. Operator Precedence Table: Precedence --> Operators
Highest ++, -- (used as prefixes); (), +, - (unary), !, ~
*, /, %
+, -
<<, >>
<, >, <=, >=
==, !=
&
^
&&
=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, =
Lowest ++, -- (used as suffixes)

The goto statements:
What are the benefits and problems of using the goto statement?
Benefit: Very simple way of controlling what code is executed when.
Problem: Excessive use of this technique can result in difficult to understand spaghetti code.
The goto statement is used as follows:
goto
and labels are defined in the following way:
:
Example:
int myInteger = 5;
goto myLabel;
myInteger += 10;
myLabel:
Console.WriteLine(“myInteger={0}”, myInteger);

What is Branching in C#?
The Branching is the act of controlling which line of code should be executed next. The line to jump to is controlled by some kind of conditional statement. The three branching techniques available in C# are:
· The ternary Operator
· The if statement
· The switch statement

What is Ternary Operator?
The simplest way of performing a comparison is to use the ternary (or conditional) operator.
Unary operator works on one operand. Binary Operator works on two operands. The Ternary Operator works on three operands.
The syntax is as follows:
? :
Example:
String result = (myInteger <10) ? “Less than 10” : “Greater then or equal to 10”; Note: This operator is fine for simple assignments such as this, but isn’t really suitable for executing larger amounts of code on a comparisons. A much better way of doing this is to use the “if “statement. How is If Statement different from the Ternary Operator? The if statement is a far more versatile and useful way of making decisions/ Like Ternary Operator the if statements don’t have a result; instead use the if statements to conditionally execute other statements.
Syntax:
If ()
{
is true>;
}
else
{
is false>;
}

Syntax:
If (var1 == 1)
{
// Do something
}
else if (var1 == 2)
{
// Do something else
}
else if (var1 == 3 var1 == 4)
{
// Do something else
}
else
{
// Do something else.
}
Note: When making multiple comparisons such as the above syntax, it can be worth considering the switch statement.

How is the Switch statement different from If statement?
The switch statement is very similar to the if statement (in this it executes code conditionally based on the value of a test). However, switch allows you to test for multiple values of a test variable in one go, rather than just a single condition.
Synatx:
Switch ()
{
case :
== >
break;
case :
== >
break;
……………
case :
== <> >
break;
default:
!= <> >
break;
}
The value in is compared to each of the values (specified with case statements), and if there is a match, then the code supplied for this match is executed. If there is no match, then the code in the default section is executed.

What is the purpose of adding break point with the break, goto, or a return in the Switch Case statements?
Adding a break point with break, goto, or return ensures that a valid execution path exists through the structure in all cases.

Do switch statements have any limit on the amount of case: sections?
Switch statements have no limit on the amount of case: sections they contain.

What is Looping in C#.NET?
Looping is when statements are executed repeatedly. It means that you can repeat operations as many times as you want without having to write the same code each time.
Types of Loops available in C# are:
· Do loops
· While loops
· For loops
· Interrupting loops
· Infinite loops

Explain the do Loops?
In do loops, the code you have marked out for looping is executed, then a Boolean test is performed, and codes executes again if this test condition is true, and so on and the loop exits when the test condition evaluates to false.
Synatx:
do
{

} whilr ();
where the evaluates to a Boolean value.
The semicolon after the while statement is required.

Example:
Int i = 1;
do
{
Console.WriteLine(“{0}”, i++);
} while (i<= 10); How is While loop different from the do loop? While loops are very similar to do loops. The Boolean test in a while loop takes place at the start of the loop cycle, not the end. If the test evaluates to false then the loop cycle is never executed. Instead, program execution jumps straight to the code following the loop Syntax: while ()
{

}

Example:
int i;
while (I <= 10) {

Console.Writeline(“{0}”, i++)
}

Explain the For Loop?
For Loop is the one that executes a set number of times and maintains its own counter. To define a for loop you need the following information:
· A starting value to initialize the counter variable
· A condition for continuing the loop, involving the counter variable
· An operation to perform on the counter variable at the end of each loop
Syntax: for (; ; )
{
}
This works in exactly the same way as the following while loop:

while loop Syntax:
while ()
{
}
Note: the format of the for loop makes the code easier to read, because the syntax involves the complete specification of the loop in one place, rather than divide it over several statements in different areas of the code.

What are the Interrupting Loops?
Interrupting Loops provide the finer-grained control over the processing of looping code. Four commands for the Interrupting Loops are as follows:


· break --> Causes the loop to end immediately, and execution continues at the first line of code after the loop.
Example:
int i;
while (I <= 10) {

if (i == 6)
break;
Console.Writeline(“{0}”, i++)
}

· continue --> causes the current loop cycle to end (stop) immediately, not the whole loop (execution continues with the next loop cycle).
Example:
int i;
for (i = 1; i <= 10; i++) {

if ((i % 2) == 0)
continue;
Console.Writeline(i);
}

· goto --> Allows jumping out of a loop to a labeled position (not recommended if you want your code to be easy to read and understand).
Example:
int i;
while (I <= 10) {

if (i == 6)
goto exitPoint;
Console.Writeline(“{0}”, i++) }
Console.WriteLine(“This code will never be reached.”);
exitPoint:
Console.WriteLine(“This code is run when the loop is exited using goto.”);

· return --> jumps out of the loop and its containing function

What are the Infinite Loops?
The loops that never end, are called as infinite loops.
Example:
While (true)
{
// code in loop
}
You can always exit infinite loops using code such as break statements or manually by using the Windows Task Manager.