Sunday, May 31, 2009

Introducing Serialization in .NET

Serialization is a process of converting an object into a stream of data so that it can be is easily transmittable over the network or can be continued in a persistent storage location. This storage location can be a physical file, database or ASP.NET Cache. Serialization is the technology that enables an object to be converted into a linear stream of data that can be easily passed across process boundaries and machines. This stream of data needs to be in a format that can be understood by both ends of a communication channel so that the object can be serialized and reconstructed easily. The advantage of serialization is the ability to transmit data across the network in a cross-platform-compatible format, as well as saving it in a persistent or non-persistent storage medium in a non-proprietary format. Serialization is used by Remoting, Web Services SOAP for transmitting data between a server and a client. De-serialization is the reverse; it is the process of reconstructing the same object later. The Remoting technology of .NET makes use of serialization to pass objects by value from one application domain to another. In this article I will discuss .NET's support for Serialization and how we can build a class that supports custom serialization.

What is Serialization and De-serialization?
[ Back To Top ]

Serialization is the process of saving the state of an object in a persistent storage media by converting the object to a linear stream of bytes. The object can be persisted to a file, a database or even in the memory. The reverse process of serialization is known as de-serialization and enables us to re-construct the object from the previously serialized instance of the same in the persistent or non-persistent storage media.

Serialization in .NET is provided by the System.Runtime.Serialization namespace. This namespace contains an interface called IFormatter which in turn contains the methods Serialize and De-serialize that can be used to save and load data to and from a stream. In order to implement serialization in .NET, we basically require a stream and a formatter. While the stream acts as a container for the serialized object(s), the formatter is used to serialize these objects onto the stream.

The basic advantage of serialization is the ability of an object to be serialized into a persistent or a non-persistent storage media and then reconstructing the same object if required at a later point of time by de-serializing the object. Remoting and Web Services depend heavily on Serialization and De-serialization. Refer to the figure below.

Figure 1

The above figure illustrates that the serialized object is independent of the storage media, i.e., it can be a database, a file or even the main memory of the system.

Advantages and Disadvantages of Serialization
[ Back To Top ]

The following are the basic advantages of serialization:

· Facilitate the transportation of an object through a network

· Create a clone of an object

The primary disadvantage of serialization can be attributed to the resource overhead (both the CPU and the IO devices) that is involved in serializing and de-serializing the data and the latency issues that are involved for transmitting the data over the network. Further, serialization is quite slow. Moreover, XML serialization is insecure, consumes a lot of space on the disk and it works on public members and public classes and not on the private or internal classes. Therefore, it compels the developer to allow the class to be accessed to the outside world.

The Serializable Attribute
[ Back To Top ]

In order for a class to be serializable, it must have the attribute SerializableAttribute set and all its members must also be serializable, except if they are ignored with the attribute NonSerializedAttribute. However, the private and public members of a class are always serialized by default. The SerializationAttribute is only used for the binary serialization. The code snippet below shows the usage of SerializableAttribute.


public class Employee
public int empCode;
public string empName;
}Note the Serializable attribute that is specified at the beginning of the class in the code listing above. The SerializableAttribute is useful for situations where the object has to be transported to other application domains. It needs to be applied even irrespective of whether the class implements the ISerializable interface. If this attribute is not set in that case, then when we try to serialize an object the CLR throws a SerializationException.

Types of Serialization
[ Back To Top ]

Serialization can be of the following types:

· Binary Serialization

· SOAP Serialization

· XML Serialization

· Custom Serialization

All these types of serialization are explained in details in the sections that follow.

Binary Serialization

Binary serialization is a mechanism which writes the data to the output stream such that it can be used to re-construct the object automatically. The term binary in its name implies that the necessary information that is required to create an exact binary copy of the object is saved onto the storage media. A notable difference between Binary serialization and XML serialization is that Binary serialization preserves instance identity while XML serialization does not. In other words, in Binary serialization the entire object state is saved while in XML serialization only some of the object data is saved. Binary serialization can handle graphs with multiple references to the same object; XML serialization will turn each reference into a reference to a unique object. The following code listing shows how we can implement binary serialization.

Listing 2:

public void BinarySerialize(string filename, Employee emp)
FileStream fileStreamObject;
fileStreamObject = new FileStream(filename, FileMode.Create);
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(fileStreamObject, emp);
}The following code listing shows how we can implement binary de-serialization.

Listing 3:

public static object BinaryDeserialize(string filename)
FileStream fileStreamObject;

fileStreamObject = new FileStream(filename, FileMode.Open);
BinaryFormatter binaryFormatter = new BinaryFormatter();
return (binaryFormatter.Deserialize(fileStreamObject));
Advantages and Disadvantages of Binary Serialization
[ Back To Top ]

One of the major advantages of using Binary Serialization in the managed environment is that the object can be de-serialized from the same data you serialized it to. Besides, the other advantage of Binary Serialization is enhanced performance as it is faster and even more powerful in the sense that it provides support for complex objects, read only properties and even circular references. However, the downside to this is that it is not easily portable to another platform.

SOAP Serialization
[ Back To Top ]

The SOAP protocol is ideal for communicating between applications that use heterogeneous architectures. In order to use SOAP serialization in .NET we have to add a reference to System.Runtime.Serialization.Formatters.Soap in the application. The basic advantage of SOAP serialization is portability. The SoapFormatter serializes objects into SOAP messages or parses SOAP messages and extracts serialized objects from the message. The following code listing shows how we can implement serialization using the SOAP protocol.

Listing 4:

public void SOAPSerialize(string filename,Employee employeeObject)
FileStream fileStreamObject = new FileStream(filename, FileMode.Create);
SoapFormatter soapFormatter = new SoapFormatter();
soapFormatter.Serialize(fileStreamObject, employeeObject);
}The following code listing shows how we can implement de-serialization using the SOAP protocol.

Listing 5:

public static object SOAPDeserialize(string filename)
FileStream fileStreamObject = new FileStream(filename, FileMode.Open);
SoapFormatter soapFormatter = new SoapFormatter();
object obj = (object)soapFormatter.Deserialize(fileStreamObject);
return obj;
XML Serialization
[ Back To Top ]

According to MSDN, "XML serialization converts (serializes) the public fields and properties of an object or the parameters and returns values of methods, into an XML stream that conforms to a specific XML Schema definition language (XSD) document. XML serialization results in strongly typed classes with public properties and fields that are converted to a serial format (in this case, XML) for storage or transport. Because XML is an open standard, the XML stream can be processed by any application, as needed, regardless of platform." Implementing XML Serialization in .Net is quite simple. The basic class that we need to use is the XmlSerializer for both serialization and de-serialization. The Web Services use the SOAP protocol for communication and the return types and the parameters are all serialized using the XmlSerializer class. XML Serialization is however, much slower compared to Binary serialization. We can set a property as an XML attribute as shown in the code listing below.

Listing 6:

public string EmpName
return empName;
empName = value;
}The following code listing shows how we can implement XML serialization.

Listing 7:

public void XMLSerialize(Employee emp, String filename)
XmlSerializer serializer = null;
FileStream stream = null;
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Create, FileAccess.Write);
serializer.Serialize(stream, emp);
if (stream != null)
}The following code listing shows how we can implement XML de-serialization.

Listing 8:

public static Employee XMLDeserialize(String filename)
XmlSerializer serializer = null;
FileStream stream = null;
Employee emp = new Employee();
serializer = new XmlSerializer(typeof(Employee));
stream = new FileStream(filename, FileMode.Open);
emp = (Employee)serializer.Deserialize(stream);
if (stream != null)
return emp;
Advantages of XML Serialization
[ Back To Top ]

The advantages of XML Serialization are as follows:

· XML based

· Support for cross platforms

· Easily readable and editable

Working with Formatters
[ Back To Top ]

A formatter is used to determine the serialization format for objects. In other words, it is used to control the serialization of an object to and from a stream. They are the objects that are used to encode and serialize data into an appropriate format before they are transmitted over the network. They expose an interface called the IFormatter interface. IFormatter's significant methods are Serialize and De-serialize which perform the actual serialization and de-serialization. There are two formatter classes provided within .NET, the BinaryFormatter and the SoapFormatter. Both these classes extend the IFormatter interface.

The Binary Formatter

The Binary formatter provides support for serialization using binary encoding. The BinaryFormater class is responsible for binary serialization and is used commonly in .NET's Remoting technology. This class is not appropriate when the data is supposed to be transmitted through a firewall.

The SOAP Formatter

The SOAP formatter provides formatting that can be used to serialize objects using the SOAP protocol. It is used to create a Soap envelop and it uses an object graph to generate the result. It is responsible for serializing objects into SOAP messages or parsing the SOAP messages and extracting these serialized objects from the SOAP messages. SOAP formatters in .NET are widely used by the Web Services.

Custom Serialization
[ Back To Top ]

In some cases, the default serialization techniques provided by .NET may not be sufficient in real life. This is when we require implementing custom serialization. It is possible to implement custom serialization in .NET by implementing the ISerializable interface. This interface allows an object to take control of its own serialization and de-serialization process. It gives us a great deal of flexibility in the way we can save and restore objects. The ISerializable interface consists of a single method, GetObjectData, which accepts two parameters.

The SerializationInfo class serves as the container for all the data we want to serialize. The AddValue method is called to add the objects we want to serialize to this container. The implementing class needs to have the GetObjectData method and a special constructor which is used by the common language runtime during the process of de-serialization. The following code listing shows how we can implement Custom Serialization.

Listing 9:

public class Employee: ISerializable
private int empCode;
private string empName;
protected Employee(SerializationInfo serializationInfo, StreamingContext
this.empCode = serializationInfo.GetInt32("empCode");
this.empName = serializationInfo.GetString("empName");
public void ISerializable.GetObjectData(SerializationInfo serializationInfo,
StreamingContext streamingContext)
serializationInfo.AddValue("empCode", this.empCode);
serializationInfo.AddValue("empName", this.empName);
}The following listing shows how we can implement Custom Serialization on a Custom Collection class that extends the CollectionBase class of the System.Collections namespace.

Listing 10

public class EmployeeCollection: System.Collections.CollectionBase,
private int empCode;

public EmployeeCollection()
empCode = 1;

protected EmployeeCollection(SerializationInfo info, StreamingContext context)
: base(info, context)
empCode = info.GetInt32("empCode");

public virtual void GetObjectData(SerializationInfo info, StreamingContext
base.GetObjectData(info, context);
info.AddValue("empCode", empCode);
Points to remember
[ Back To Top ]

This section deals with some of the points that we have already covered in this article and some others that we have not, but are still very important and relate to the serialization and de-serialization concepts of .NET.

When you apply the Serializable custom attribute to a type, all instance fields of the class (public, private, protected, etc.) are serialized automatically.

XmlSerializer does not use the ISerializable interface; rather, it uses the IXmlSerializable interface. The XmlSerializer class can only serialize the public properties of the class, whereas the BinaryFormatter class can serialize private fields using the ISerializable interface.

The Serializable attribute is a must for making a class serializable irrespective of whether we have implemented the ISerializable interface in this class. When we serialize a class, the objects of the references to other classes that are contained in this class are also serialized if they are marked as serializable. All members are serialized, including public, private or protected members. Furthermore, even circular references are supported by binary serialization. Note that read only properties are not serialized except the collection class objects. However, the read only properties can be serialized using binary serialization.

If we do not require serializing a particular property of a class when using an XmlSerializer, we have to mark the property with the custom attribute XmlIgnoreAttribute. When using a SoapFormatter we have to use the SoapIgnoreAttribute instead. The XmlSerializer generates an in-memory assembly optimized for each type since the initial invocation to a Web Service always takes so much time. To combat this, we can use the sgen.exe tool to pre-generate the serialization assembly.

[ Back To Top ]

Serialization/Deserialization in .NET

Serialization in .NET

Serialization in .NET


[ Back To Top ]

Serialization is the process of storing an object, including all of its members, to a persistent or a non-persistent storage media by converting the object into a linear stream of data. De-serialization is the process of restoring an object's values from the said stream. The advantage of serialization is to save the state of an object in order to have the ability to recreate the same object at a later point of time if and when it is required. The .NET Framework provides a strong support for serialization of objects. The .NET Framework provides a unified standard for serializing and de-serializing objects for building distributed heterogeneous systems. This article has explored Serialization and De-serialization and the various types of Serialization concepts with code examples wherever necessary. It has discussed what Custom Serialization is and how to implement it. However, I would recommend not using serialization unless it is absolutely necessary due to the drawbacks that I have already explained in this article. I hope that the readers will find this article quite useful and post their comments and suggestions on this article. Happy reading!

Wednesday, May 27, 2009

DOT NET Questions Part 2

1. Briefly describe the major components of the .NET Framework and describe what each component does.
The .NET Framework consists of two primary parts: the common language runtime, which manages application execution, enforces type safety, and manages memory reclamation, and the .NET base class library, which consists of thousands of predeveloped classes that can be used to build applications.

2. Briefly explain what is meant by a reference type and a value type.
A value type holds all of the data represented by the variable within the variable itself. A reference type contains a reference to a memory address that holds the data instead of the actual data itself.

3. How do you enable your application to use .NET base class library members without referencing their fully qualified names?
Use the Imports keyword (Visual Basic .NET) or the using keyword (Visual C#) to make a .NET Framework namespace visible to your application.

4. Briefly describe how garbage collection works.
The garbage collector is a thread that runs in the background of managed .NET applications. It constantly traces the reference tree and attempts to find objects that are no longer referenced. When a nonreferenced object is found, its memory is reclaimed for later use.

5. Briefly describe what members are, and list the four types of members.
Members are the parts of a class or a structure that hold data or implement functionality. The primary member types are fields, properties, methods, and events.

6. Explain what constructors and destructors are and describe what they are used for.
The constructor is the method that initializes a class or structure and is run when a type is first instantiated. It is used to set default values and perform other tasks required by the class. A destructor is the method that is run as the object is being reclaimed by garbage collection. It contains any code that is required for cleanup of the object.

7. Briefly explain the difference between Public (public), Friend (internal), and Private (private) access levels as they apply to user-defined types and members.
In user-defined types, Public (public) classes can be instantiated by any element of the application. Friend (internal) classes can be instantiated only by members of the same assembly, and Private (private) classes can be instantiated only by themselves or types they are nested in. Likewise, a Public (public) member can be accessed by any client in the applica-tion, a Friend (internal) member can be accessed only from members of the same assembly, and Private (private) members can be accessed only from within the type.

8. Do you need to instantiate a class before accessing a Shared (static) member? Why or why not?
Because a Shared (static) member belongs to the type rather than to any instance of the type, you can access the member without first creating an instance of the type.

1. You are creating an application for a major bank. The application should integrate seamlessly with Microsoft Office XP, be easy to learn, and instill a sense of corporate pride in the users. Name two ways you might approach these goals in the user interface.
Design the user interface to mimic the look and feel of Microsoft Office XP, which will allow users of Office XP to immediately feel comfortable with the new application. Integration of the corporate logo and other visual elements associated with the company will aid in identification of the program with the company.

2. You are writing an application that needs to display a common set of controls on several different forms. What is the fastest way to approach this problem?
Create a single form that incorporates the common controls, and use visual inheritance to create derived forms.

3. If you wanted to prompt a user for input every time a form received the focus, what would be the best strategy for implementing this functionality?
Write an event handler for the Activated event that implements the relevant functionality.

4. Describe two ways to set the tab order of controls on your form.
You can set the tab order in Visual Studio by choosing Tab Index from the View menu and clicking each control in the order you desire. Alternatively, you can set the TabIndex property either in code or in the Properties window.

5. What is an extender provider, and what does one do?
Extender providers are components that provide additional properties to controls on a form. Examples include the ErrorProvider, HelpProvider, and ToolTip components. They can be used to provide additional information about particular controls to the user in the user interface.

6. Explain when you might implement a shortcut menu instead of a main menu.
If every possible option is exposed on a main menu, the menu can become busy and hard to use. Shortcut menus allow less frequently used options to be exposed only in situations where they are likely to be used.

7. Describe what is meant by field-level validation and form-level validation.
Field-level validation is the process of validating each individual field as it is entered into a form. Form-level validation describes the process of validating all of the data on a form before submitting the form.

1. Explain when a type conversion will undergo an implicit cast and when you must perform an explicit cast. What are the dangers associated with explicit casts?
Types can be implicitly converted when the conversion can always take place without any potential loss of data. When a potential loss of data is possible, an explicit cast is required. If an explicit cast is improperly performed, a loss of data precision can result, or an exception can be thrown.

2. Explain why you might use enums and constants instead of their associated literal values.
Enums and constants make code easier to read and maintain by substituting human-legible tokens for frequently used constant values.

3. Briefly summarize the similarities and differences between arrays and collections.
Arrays and collections allow you to manage groups of objects. You can access a particular object by index in both arrays and collections, and you can use For Each...Next (foreach) syntax to iterate through the members of arrays and most collections. Arrays are fixed in length, and members must be initialized before use. Members of collections must be declared and initialized outside of the collection, and then added to the collection. Collections provided in the System.Collections namespace can grow or shrink dynamically, and items can be added or removed at run time.

4. Explain how properties differ from fields. Why would you expose public data through properties instead of fields?
Properties allow validation code to execute when values are accessed or changed. This allows you to impose some measure of control over when and how values are read or changed. Fields cannot perform validation when being read or set.

5. Explain what a delegate is and how one works.
A delegate acts like a strongly typed function pointer. Delegates can invoke the methods that they reference without making explicit calls to those methods.

1. Briefly explain encapsulation and why it is important in object-oriented programming.
Encapsulation is the principle that all of the data and functionality required by an object be contained by that object. This allows objects to exist as independent, interchangeable units of functionality without maintaining dependencies on other units of code.

2. What is method overloading, and when is it useful?
Method overloading allows you to create several methods with the same name but different signatures. Overloading is useful when you want to provide the same or similar functionality to different sets of parameters.

3. You need to create several unrelated classes that each exposes a common set of methods. Briefly outline a strategy that will allow these classes to polymorphically expose that functionality to other classes.
Factor the common set of methods into an interface, and then implement that interface in each class. Each class can then be implicitly cast to that interface and can polymorphically interact with other classes.

4. You need to create several classes that provide a core set of functionality but each must be able to interact with a different set of objects. Outline a strategy for developing these classes with the least development time.
Create a single class that implements all of the common functionality required by these classes. Then, use inheritance to create derived classes that are specific for each individual case.

5. Describe an abstract class and explain when one might be useful.
An abstract class is a class that cannot be instantiated but must be inherited. It can contain both implemented methods and abstract methods, which must be implemented in an inheriting class. Thus, it can define common functionality for some methods, a common interface for other methods, and leave more detailed implementation up to the inheriting class.

1. Describe Break mode and some of the available methods for navigating in Break mode.
Break mode allows you to observe program execution on a line-by-line basis. You can navigate program execution in Break mode by using Step Into, Step Over, Step Out, Run To Cursor, and Set Next Statement.

2. When would you use the Watch window?
You would use the Watch window to observe the values of application variables while in Break mode.

3. You are deploying a beta version of a large application and want to collect performance data in text files while the application is in use. Briefly describe a strategy for enabling this scenario.
Place Trace statements that report the data of interest throughout the application. Create a TextWriterTraceListener and add it to the Listeners collection. Create Trace switches that control when Trace statements are executed. Configure the TextWriterTraceListener to write output to a text file. Then, compile and deploy the application with Trace defined, and enable the Trace switches in the application .config file.

4. When testing a method, should you test data that is known to be outside of the bounds of normal operation? Why or why not?
Yes. In addition to testing normal data operation, you must test known bad input to ensure that your application can recover from input errors without a catastrophic application failure.

5. Briefly explain what each segment of a Try...Catch...Finally (try...catch...finally) block does.
The Try (try) block encloses code that is to be executed. If an exception is thrown, it can be caught in an appropriate Catch (catch) block where code that will allow the application to handle the execution will be executed. The Finally (finally) block contains any code that must be executed whether or not the exception is handled.

1. What are the major components of a Data Provider, and what function does each fulfill?
An ADO.NET Data Provider is a suite of components designed to facilitate data access. Every Data Provider minimally includes a Connection object that provides the actual connection to the data source, a Command object that represents a direct command to the data source, a DataReader object that provides connected, forward-only, read-only access to a database, and a DataAdapter that facilitates disconnected data access.

2. Briefly contrast connected and disconnected data access in ADO.NET.
In ADO.NET, connected data access is available through the DataReader, which is a lightweight class designed to provide very fast and efficient data access. It is severely limited, however, in that it can only provide forward-only data access, it does not allow editing, and it requires the exclusive use of a Connection object. In contrast, disconnected data access is facilitated by a DataAdapter, which manages the commands required for selecting and updating data. The DataAdapter executes a SELECT command against a database, opening a data connection just long enough to retrieve the data, and loads the data into a DataSet, which is an in-memory copy of the data. When the data is ready to be updated, the Data Provider manages the updates in the same way, generating the appropriate commands to update the database and keeping the connection open just long enough to execute those commands.

3. What are the three possible settings for the CommandType property of a SqlCommand object or an OleDbCommand object, and what does each mean?
A Command object can have a CommandType property setting of Text, StoredProcedure, or TableDirect. When set to Text, the command executes the SQL string that is stored in the Command object's CommandText property. When set to StoredProcedure, the command accesses a procedure stored on the database and returns the results. A CommandText setting of TableDirect indicates that the command should return the entire contents of the table indicated by the CommandText property.

4. How could you execute DDL commands, such as ALTER or CREATE TABLE, against a database with ADO.NET?
You must use a Command object to execute DDL commands. You can set the CommandType property to Text and enter the appropriate DDL command in the CommandText property. Then call Command.ExecuteNonQuery to execute the command.

5. Briefly discuss the advantages and disadvantages of using typed DataSet objects.
Typed DataSet objects allow you to work with data that is represented as members of the .NET common type system. This allows your applications to be aware of the types of data returned in a DataSet and serves to eliminate errors resulting from invalid casts, as any type mismatches are caught at compile time. Untyped DataSet objects, however, are useful if you do not know the structure of your data, and can be used with any data source.

6. How can you manage data currency on a form with several bound controls?
Every data source on a form has an associated CurrencyManager object that keeps that of the "current" record with respect to bound controls. For convenience, all of the CurrencyManager objects represented on a form are exposed through the form's BindingContext property. The Position of the CurrencyManager can be changed, allowing navigation through the records.

7. Describe how to use a DataView to filter or sort data.
You can apply sort criteria to a DataView by setting the Sort property to the name of a column or columns to be sorted by. The data represented in a DataView object can be filtered by setting the RowFilter property to a valid filter expression.

8. Briefly describe an XmlDataDocument and how it relates to a DataSet.
An XmlDataDocument is an in-memory representation of data in a hierarchical Xml format. Each XmlDataDocument is synchronized with a DataSet. Whenever changes are made to one object, the other is instantly updated. Thus, you can use the XmlDataDocument to perform XML manipulations on a DataSet.

1. Briefly describe the three types of user-developed controls and how they differ.
The three types of user-developed controls are inherited controls, user controls, and custom controls. An inherited control derives from a standard Windows Forms control and inherits the look, feel, and functionality of that control. User controls allow you to combine standard Windows Forms controls and bind them together with common functionality. Custom controls inherit from Control and are the most development-intensive kind of control. Custom controls must implement all their own code for painting and inherit only generic control functionality. All specific functionality must be implemented by the developer.

2. Describe the roles of Graphics, Brush, Pen, and GraphicsPath objects in graphics rendering.
The Graphics object represents a drawing surface and encapsulates methods that allow graphics to be rendered to that surface. A Brush is an object that is used to fill solid shapes, and a Pen is used to render lines. A GraphicsPath object represents a complex shape that can be rendered by a Graphics object.

3. Describe the general procedure for rendering text to a drawing surface.
You must first obtain a reference to a Graphics object. Next, create an instance of a GraphicsPath object. Use the GraphicsPath.AddString method to add text to the GraphicsPath. Then, call the Graphics.DrawPath or Graphics.FillPath to render the text.

4. Describe the role of the LicenseProvider in control licensing.
The LicenseProvider controls license validation and grants run-time licenses to validly licensed components. The LicenseManager.Validate method checks for an available license file and checks against the validation logic provided by the specific implementation of LicenseProvider. You specify which LicenseProvider to use by applying the LicenseProviderAttribute.

5. Describe how to create a form or control with a nonrectangular shape.
Set the Region property of the form or control to a Region object that contains the irregular shape. You can create a Region object from a GraphicsPath object.

1. Briefly describe how to use the PrintDocument component to print a document. Discuss maintaining correct line spacing and multipage documents.
The PrintDocument class exposes the Print method, which raises the PrintPage event. Code to render printed items to the printer should be placed in the PrintPage event handler. The PrintPage event handler provides the objects required to render to the printer in an instance of the PagePrintEventArgs class. Content is rendered to the printer using the Graphics object provided by PagePrintEventArgs. You can calculate correct line spacing by dividing the height of the MarginBounds property by the height of the font you are rendering. If your document has multiple pages, you must set the PagePrintEventArgs.HasMorePages property to true, which causes the PrintPage event to fire again. Because the PrintPage event handler retains no inherent memory of how many pages have been printed, you must incorporate all logic for printing multiple pages into your event handler.

2. Explain how to use the Begin and End methods on a Web Service to make an asynchronous method call.
Every public Web method on a Web Service can be called either synchronously or asynchronously. To make an asynchronous call to a Web method, you call the method named Begin, where is the name of the method. This method requires a delegate to an appropriate callback method and returns a value of IAsyncResult. This value is returned as a parameter in the callback method. To retrieve the data returned by the Web method, call End, supplying a reference to the IAsyncResult returned by Begin. This will allow you to retrieve the actual data returned by the Web method.

3. Briefly describe the five accessibility requirements of the Certified for Windows logo program.
The five requirements are
o Support standard system settings. This requires your application to be able to conform to system settings for colors, fonts, and other UI elements.
o Be compatible with High Contrast mode. This requirement can be met by using only the System palette for UI colors.
o Provide documented keyboard access for all UI features. Key points in this requirement are shortcut keys and accessible documentation.
o Provide notification of the focus location. This requirement is handled primarily by the .NET Framework.
o Convey no information by sound alone. This requirement can be met by providing redundant means of conveying information.

4. Explain how to use the HelpProvider component to provide help for UI elements.
You can provide either a HelpString or a help topic for UI elements with the HelpProvider. The HelpProvider provides HelpString, HelpKeyWord, and HelpNavigator properties for each control on the form. If no value for the HelpProvider.HelpNameSpace is set, the HelpString will be provided as help. If the HelpNameSpace is set, the HelpProvider will display the appropriate help topic as configured by the HelpKeyWord and HelpNavigator properties. Help for a particular element is displayed when the element has the focus and the F1 key is pressed.

5. Describe how to create localized versions of a form.
To create a localized version of a form, set the Localizable property to true. Then set the Language property to the language/region for which you want to create the localized form. Make any localization-related changes in the UI. The changed property values will automatically be stored in resource files and loaded when the CurrentUICulture is set to the appropriate CultureInfo.

6. Explain how to convert data in legacy code page formats to the Unicode format.
You can use the Encoding.Convert method to convert data between encoding types. This method requires instances of both encoding types and an array of bytes that represents the data to be converted. It returns an array of bytes in the target format. You can convert a string or array of chars to an array of bytes with the Encoding.GetBytes method and can convert an array of bytes back to chars with the Encoding.GetChars method.

7. Explain the difference between Globalization and Localization.
Globalization refers to the application of culture-specific format to existing data. Localization refers to providing new culture-specific resources and retrieving the appropriate resources based on the culture setting

1. Describe how to sign your assembly with a strong name. Why would you want to do this?
To sign your assembly with a strong name, you must have access to a key file or create one with the strong name utility (sn.exe). You then specify the key file in the AssemblyInfo file and verify that the version number is correct. The assembly will be signed with a strong name when built. In addition to identifying your assembly and ensuring version identity, a strong name is required if you want to install your assembly to the Global Assembly Cache.

2. Describe how to use code to retrieve resources at run time.
You must first create an instance of the ResourceManager class that is associated with the assembly that contains the desired resource. You can then use the GetString method to retrieve string resources or the GetObject method to retrieve object resources.

3. Explain how to retrieve information from the configuration file at run time. How would you store information in the configuration file at design time?
You must first create an instance of AppSettingsReader to read the configuration file. You can then call the GetValue method to read values represented in the configuration file. To add configuration file entries, you should create elements in the node of the configuration file. In the element, you should specify a value for the entry and a key that can be used to retrieve the entry. The value can be changed between executions of the application.

4. You are creating a solution that must be accessed by members of a group called Developers and Administrators on the local machine. Describe a plan to implement this security scheme.
Create one PrincipalPermission that represents the Developers group and another PrincipalPermission that represents the BUILTIN\Administrators group. Then, create a third permission that represents the union of the two by calling the Union method and demand that permission.

5. Briefly highlight the differences between imperative and declarative security as they pertain to code access security.
Imperative security is implemented by calling methods of Permission objects in code at run time. Declarative security is configured by attaching attributes representing permissions to classes and methods. Imperative security allows a finer control over the point in execution where permissions are demanded, but declarative security is emitted into metadata, and required permissions can be discovered through the classes in the System.Reflection namespace. Additionally, you can request assembly-wide permissions using the Assembly (assembly) directive with declarative security.

1. Describe XCOPY deployment. Under what conditions is it useful? When can it not be used?
XCOPY deployment is a simple method of deployment where the DOS command XCOPY is used to copy the application directory and any subdirectories to the target machine. You can use XCOPY deployment if your application has no dependency on shared files and requires no special actions to be taken upon deployment. If an application requires a more complex deployment or references shared assemblies, you cannot use XCOPY.

2. You have created an application for a client who wants to distribute your application to his workforce via a network share. He wants to ensure that everyone who downloads the application will download it to the same folder. Describe a plan that would accomplish this goal.
Create a setup project for the application. Using the User Interface Editor, provide a dialog box that allows the file directory to be set during administrative installation, but removes this box from regular installation. Use administrative installation to install the application to the network share.

3. You have written documentation for your application and have provided it in the form of several HTML files. Describe two ways you could include this content in your setup project.
You can include loose HTML files along with your application by either including them when you create the setup project with the Setup wizard or by adding them to the project after creation with the File System Editor.

4. What is a native image? How do you create one?
A native image is a precompiled version of a .NET assembly. You can create a native image of your application by using the Ngen.exe utility.

5. What is the purpose of a bootstrapper application? When do you not need to create one?
A bootstrapper application automatically detects if Windows Installer is installed on the target machine. If Windows Installer is not present, it installs Windows Installer before proceeding with the rest of the installation. You should create a bootstrapper application unless all of your target machines are running Windows XP (which has Microsoft Windows Installer 1.5 already installed) or have had Microsoft Installer 1.5 installed previously.

ASP.NET Questions

1. Response.Redirect sends a response back to the browser and tells it to open the URL you pass it. Server.Transfer actually transfers the request from one page to another, never leaving the server. That is why you can not server.transfer to another domain. Each have their place, Response.Redirect is used more often than server.transfer, but I think that is because so many learned to do that in the old ASP days. With transfer you actually retain access to the objects of the page that initiated the post-back, where with Response.Redirect you would have to pass a set of querystring parameters.

2. response.Write add text to the buffer being sent to the browser
3. Web applications. These provide content from a server to client machines over the Internet. Users view the Web application through a Web browser, such as Microsoft Internet Explorer or Netscape Navigator.(System.web.namespace)
4. Web services. These components provide processing services from a server to other applications over the Internet. .(SystemWeb.Services.namespace)
5. Internet-enabled applications. These are stand-alone applications that incorporate aspects of the Internet to provide online registration, Help, updates, or other services to the user over the Internet. .(System.Net.namespace)
6. Peer-to-peer applications. These are stand-alone applications that use the Internet to communicate with other users running their own instances of the application. .(System.Net.Socket.namespace)
7. Web applications use a client/server architecture. The Web application resides on a server and responds to requests from multiple clients over the Internet
· On the client side, the Web application is hosted by a browser, such as Internet Explorer or Netscape Navigator
· On the server side, the Web application runs under Microsoft Internet Information Services (IIS). IIS manages the application, passes requests from clients to the application, and returns the application' s responses to the client. These requests and responses are passed across the Internet using Hypertext Transport Protocol (HTTP).
· protocol is a set of rules that describe how two or more items communicate over a medium
8. ASP.NET is the platform that you use to create Web applications and Web services that run under IIS. ASP.NET is part of the .NET Framework and is made up of several different components.
· Visual Studio .NET Web development tools. These include visual tools for designing Web pages and application templates, project management, and deployment tools for Web applications.
· The System.Web namespaces. These are part of the .NET Framework, and include the programming classes that deal with Web-specific items such as HTTP requests and responses, browsers, and e-mail.
· Server and HTML controls. These are the user-interface components that you use to gather information from and provide responses to users.
These items aren' t part of ASP.NET. However, they are key to ASP.NET programming.
· Microsoft Internet Information Services (IIS). As mentioned in the previous section, IIS hosts Web applications on the Windows server.
· The Microsoft Visual Basic .NET, Microsoft Visual C#, and JScript programming languages. These three languages have integrated support in Visual Studio .NET for creating Web applications.
· The .NET Framework. This is the complete set of Windows programming classes; they include the ASP.NET classes as well as classes for other programming tasks such as file access, data type conversion, array and string manipulation, and so on.
· ADO.NET database classes and tools. These components provide access to Microsoft SQL Server and ODBC databases. Data access is often a key component of Web applications.
· Microsoft Application Center Test (ACT). This Visual Studio .NET component provides an automated way to stress-test Web applications.
9. The most significant advantage is its integration with the Windows server and programming tools. Web applications created with ASP.NET are easier to create, debug, and deploy because those tasks can all be performed within a single development environment—Visual Studio .NET.
10. A Web form is a cross between a regular HTML page and a Windows form: but it also has controls that respond to events and run code, like a Windows form.
11. Components on a Web Form
· Server controls
TextBox, Label, Button, ListBox, DropDownList, DataGrid
These controls respond to user events by running event procedures on the server. Server controls have built-in features for saving data that the user enters between page displays. You use server controls to define the user interface of a Web form.
· HTML controls
Text area, Table, Image, Submit Button, Reset Button
These represent the standard visual elements provided in HTML. HTML controls are useful when the more complete feature set provided by server controls is not needed.
· . Data controls
SqlConnection, SqlCommand, OleDbConnection, OleDbCommand, DataSet
Data controls provide a way to connect to, perform commands on, and retrieve data from SQL and OLE databases and XML data files.
· System components
FileSystemWatcher, EventLog, MessageQueue
These components provide access to various system-level events that occur on the server

it possible to inline assembly or IL in C# code? - No.
2. Is it possible to have different access modifiers on the get/set methods of a property? - No. The access modifier on a property applies to both its get and set accessors. What you need to do if you want them to be different is make the property read-only (by only providing a get accessor) and create a private/internal set method that is separate from the property.
3. Is it possible to have a static indexer in C#? - No. Static indexers are not allowed in C#.
4. If I return out of a try/finally in C#, does the code in the finally-clause run? - Yes. The code in the finally always runs. If you return out of the try block, or even if you do a “goto” out of the try, the finally block always runs:
using System;

class main
public static void Main()
Console.WriteLine("In Try block");
Console.WriteLine("In Finally block");
Both “In Try block” and “In Finally block” will be displayed. Whether the return is in the try block or after the try-finally block, performance is not affected either way. The compiler treats it as if the return were outside the try block anyway. If it’s a return without an expression (as it is above), the IL emitted is identical whether the return is inside or outside of the try. If the return has an expression, there’s an extra store/load of the value of the expression (since it has to be computed within the try block).
5. I was trying to use an “out int” parameter in one of my functions. How should I declare the variable that I am passing to it? - You should declare the variable as an int, but when you pass it in you must specify it as ‘out’, like the following: int i; foo(out i); where foo is declared as follows: [return-type] foo(out int o) { }
6. How does one compare strings in C#? - In the past, you had to call .ToString() on the strings when using the == or != operators to compare the strings’ values. That will still work, but the C# compiler now automatically compares the values instead of the references when the == or != operators are used on string types. If you actually do want to compare references, it can be done as follows: if ((object) str1 == (object) str2) { … } Here’s an example showing how string compares work:
7. using System;
8. public class StringTest
9. {
10. public static void Main(string[] args)
11. {
12. Object nullObj = null; Object realObj = new StringTest();
13. int i = 10;
14. Console.WriteLine("Null Object is [" + nullObj + "]n"
15. + "Real Object is [" + realObj + "]n"
16. + "i is [" + i + "]n");
17. // Show string equality operators
18. string str1 = "foo";
19. string str2 = "bar";
20. string str3 = "bar";
21. Console.WriteLine("{0} == {1} ? {2}", str1, str2, str1 == str2 );
22. Console.WriteLine("{0} == {1} ? {2}", str2, str3, str2 == str3 );
23. }
24. }
Null Object is []
Real Object is [StringTest]
i is [10]
foo == bar ? False
bar == bar ? True
25. How do you specify a custom attribute for the entire assembly (rather than for a class)? - Global attributes must appear after any top-level using clauses and before the first type or namespace declarations. An example of this is as follows:
26. using System;
27. [assembly : MyAttributeClass] class X {}
Note that in an IDE-created project, by convention, these attributes are placed in AssemblyInfo.cs.
28. How do you mark a method obsolete? -
[Obsolete] public int Foo() {...}
[Obsolete("This is a message describing why this method is obsolete")] public int Foo() {...}
Note: The O in Obsolete is always capitalized.
29. How do you implement thread synchronization (Object.Wait, Notify,and CriticalSection) in C#? - You want the lock statement, which is the same as Monitor Enter/Exit:
30. lock(obj) { // code }
translates to
try {
// code
31. How do you directly call a native function exported from a DLL? - Here’s a quick example of the DllImport attribute in action:
32. using System.Runtime.InteropServices;
33. class C
34. {
35. [DllImport("user32.dll")]
36. public static extern int MessageBoxA(int h, string m, string c, int type);
37. public static int Main()
38. {
39. return MessageBoxA(0, "Hello World!", "Caption", 0);
40. }
41. }
This example shows the minimum requirements for declaring a C# method that is implemented in a native DLL. The method C.MessageBoxA() is declared with the static and external modifiers, and has the DllImport attribute, which tells the compiler that the implementation comes from the user32.dll, using the default name of MessageBoxA. For more information, look at the Platform Invoke tutorial in the documentation.
42. How do I simulate optional parameters to COM calls? - You must use the Missing class and pass Missing.Value (in System.Reflection) for any values that have optional parameters.

1. Why are Server control tags shown in the browser instead of the controls it represents?
This is because the server control tags were not converted into their respecting HTML element tags by ASP.Net. This happens when ASP.Net is not properly registered with IIS. .Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe use the command: aspnet_regiis.exe -u ---> to uninstall current version. use the command: aspnet_regiis.exe -i ---> to install current version
2. What are the Best practices for side-by-side execution of Framework 1.1 and 2.0?
In ASP.NET, applications are said to be running side by side when they are installed on the same computer, but use different versions of the .NET Framework.
3. Can I have VS.NET and the Visual Studio 6.0 installed on the same machine?
Yes! VS.Net works with the .Net framework, while VS6.0 works with MFC or the Windows API directly, for the most part. They can be installed and run on the same machine without any considerations.
4. What is Assembly name and name space?
An assembly is a logical unit of code. Physically it may exist as dll or an exe. which can contain one or more files and they can be any file types like image files, text files etc. along with DLLs or EXEs.When you compile your source code by default the exe/dll which is generated is actually an assemblyand every assembly file contains information about itself which is called as Assembly Manifest.Namespace is an abstract container providing context for the items it holds and allows disambiguation of items having the same name (residing in different namespaces. It can also be said as a context for identifiers. So under a namespace you can have multiple assemblies.
5. what is capacity of dataset?
DataSet is logical represantation of database so it can store as much as database.
6. What is deployment? How do you deploy .Net and Java applications
Deployment - It is the procedure to deploy Web Application on the Server. You can deploy .Net application by simply Xcopy and create virtual directory for the application on server.
7. Where this DataSet is Stored?
Dataset is an in-memory representation of a database. Its stored no where but in memory. Goes off when GC stats after a littl sleep.
8. How different are interface and abstract class in .Net?
When a class is not provided with full functionalitythen it is declared as doesn't support instance creation as well as it cannot be overridable to child class.interface is a colection of methods only without functionality.interface is 90% same as abstract class.
9. How does 2005 support biztalkserver?
if you install biztalk server it provides Biztalk Project in the project types like webproject, windows project, console project. We use rest of the products of the Biztalk like adapters and all those thing and use them in .net.
10. what is marshling?
Marshaling performs the necessary conversions in data formats between managed and unmanaged code.CLR allows managed code to interoperate with unmanaged code usining COM Marshaler(Component of CLR).
11. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?
o A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
o A DataSet is designed to work without any continuing connection to the original data source.
o Data in a DataSet is bulk-loaded, rather than being loaded on demand.
o There's no concept of cursor types in a DataSet.
o DataSets have no current record pointer You can use For Each loops to move through the data.
o You can store many edits in a DataSet, and write them to the original data source in a single operation.
o Though the DataSet is universal, other objects in ADO.NET come in different versions for different data sources.
12. In .NET Compact Framework, can I free memory explicitly without waiting for garbage collector to free the memory?
.NET Compact Framework come with CLR which perform automatic garbage collector to free the memory without using destector(perform garbage collector when is declear)
1. What is ASP.NET?
ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications
2. Why does my ASP.NET file have multiple form tag with runat=server?
This means that ASP.Net is not properly registered with IIS.
.Net framework provides an Administration utility that manages the installation and uninstallation of multiple versions of ASP.NET on a single machine. You can find the file in C:\WINNT\Microsoft.NET\Framework\v**\aspnet_regiis.exe
3. How to find out what version of ASP.NET I am using on my machine?
Response.Write(System.Environment.Version.ToString() )
4. Is it possible to pass a querystring from an .asp page to aspx page?
Yes you can pass querystring from .asp to ASP.NET page .asp
response.redirect "webform1.aspx?id=11
5. What is a ViewState?
View State Allows the state of objects to be Stored in Hidden Fields.In ASP .NET, when the form is submitted the form reappears in the browser with all form values.
6. Where can I get the details on Migration of existing projects using various technologies to ASP.NET?
Microsoft has designed Migration Assistants to help us convert existing pages and applications to ASP.NET. It does not make the conversion process completely automatic, but it will speed up project by automating some of the steps required for migration. Below are the Code Migration Assistants
ASP to ASP.NET Migration Assistant
PHP to ASP.NET Migration Assistant
JSP to ASP.NET Migration Assistant
7. What is the equivalent of date() and time() in ASP.NET?
8. How to prevent a button from validating it's form?
Set the CauseValidation property of the button control to False
9. How to catch the 404 error in my web application and provide more useful information?
In the global.asax Application_error Event write the following code.
10. How can I change the action of a form through code?
You can't change it. The action attribute is owned by ASP.NET. Handle Events and Transfer.
11. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?
DataTextField property.
12. What is the transport protocol you use to call a Web service?
SOAP (Simple Object Access Protocol) is the preferred protocol.
13. What does WSDL stand for?
Web Services Description Language
14. What is the Global.asax used for?
The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
1. When was ASP.NET released?
ASP.NET is a part of the .NET framework which was released as a software platform in 2002.
2. What is CLR?
Common Language Runtime (CLR) is a run-time environment that manages the execution of .NET code and provides services like memory management, debugging, security, etc.
3. In Visual Studio .NET, how do I create a new ASP.NET application for an existing ASP.NET project?
First create an IIS application using the IIS MMC. Then in Visual Studio .NET, use the "New Project In Existing Folder" project template (at the end of the template list). It will first ask you for the project name (use the same one you created for the IIS application). Click OK button. Then enter in physical folder location.
4. What is the Difference between HTML controls and Controls?
HTML controls are run on client side, where as controls runs on server side and for execute on client side, they generate HTML controls.
5. Can a .NET web application consume Java web service ?
Yes.Actually Webservices are independent to language. it depends on WSDL and SOAP. so any one can develope the Webservices anddisclose the wsdl and users can cosume the webservices.wsdl and soap both are xml based.. and all languages having xml parsing capability and access to http protocol will be able to work with Webservices
6. how to click or select a row in gridview using c# code?
We should use the Currency CurrencyManager cmGrid = (CurrencyManager)this.BindingContext[gridview.DataSource, gridview.DataMember]; cmGrid.Position = iIndex;
7. What is IPostBack? How to use it?
Ispostback event is generated by the web controls to alert the server to take respected action of the event generated. When the button is clicked then click event is generated which further cause ispostback event & it alerts the server to take respected action during postback event.
8. ColumnMapping belongs to which namespaces?
ColumnMapping belongs to System.Data
9. Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component
when there is no .Net framework installed in one of the communicating applications
10. In order to get assembly info whcih namespace we should import?
11. Which method do you invoke on the DataAdapter control to load your generated dataset with data?
dataadapter.fill(dataset object)
12. Enumerate the types of Directives?
o @ Page directive
o @ Assembly directive
o @ Import directive
o @ Reference directive
o @ Implements directive
o @ OutputCache directive
o @ Register directive
13. What is a DataReader?
A DataReader is a read-only stream of data returned from the database as the query executes. It only contains one row of data in memory at a time and is restricted to navigating forward only in the results one record at a time. The DataReader does support access to multiple result sets, but only one at a time and in the order retrieved. Just as in the original version of ADO, the data is no longer available through the DataReader once the connection to the data source is closed, which means a DataReader requires a connection to the database throughout its usage. Output parameters or return values are only available through the DataReader once the connection is closed.
14. Why DataReader Useful?
Data Reader is Read only version Data Set,Each record is returned as a Data Reader Object,ExecuteReader method acts directly on the database connection. There are two versions of the data reader object: OleDbDataReader and SqlDataReader
15. Differnce B/w DataReader and DataSet
The Dataset is an core of disconnected architecture.Disconnected architecture means once you have retriveed the data from the database the connect of the datasource is dropped.The disconnected data become very commonlyThe dataset for the disconnected data from the Dataset object.The DataReader is an readonly ,forward only stream from the database.While using the datareader can improve the application performance reduce the system overhead because only one buffer row at a time in memory.
1. What is the smallest unit of execution in .NET?
An Assembly.
2. How is .NET able to support multiple languages?
a language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.
3. What’s a satellite assembly?
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core application separately from the localized modules, the localized assemblies that modify the core application are called satellite assemblies.
4. What’s the difference between the Debug class and Trace class?
Use Debug class for debug builds, use Trace class for both debug and release builds.
5. How is the DLL Hell problem solved in .NET?
Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.
6. What are the ways to deploy an assembly?
An MSI installer, a CAB archive, and XCOPY command.
7. When should you call the garbage collector in .NET?
As a good rule, you should not call the garbage collector. However, you could call the garbage collector when you are done using a large object (or set of objects) to force the garbage collector to dispose of those very large objects from memory. However, this is usually not a good practice.
8. How do you convert a value-type to a reference-type?
Use Boxing.
9. Whats an assembly?
Assemblies are the building blocks of the .NET framework;
10. What happens in memory when you Box and Unbox a value-type?
Boxing converts a value-type to a reference-type, thus storing the object on the heap. Unboxing converts a reference-type to a value-type, thus storing the value on the stack.
11. Is .NET capable of supporting multi-thread?
yes, .net supports multithreading which is one of the feature supported by .net
12. What does assert() do?
In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.
13. Can you store multiple data types in System.Array?
14. Where does the Web page belong in the .NET Framework class hierarchy?
15. Where do you store the information about the user’s locale?
16. Whats MSIL, and why should my developers need an appreciation of it if at all?
MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL.
17. How many classes can a single .NET DLL contain?
It can contain many classes.
18. What is the role of the DataReader class in ADO.NET connections?
It returns a read-only, forward-only rowset from the data source. A DataReader provides fast access when a forward-only sequential read is needed.
19. What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?
SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix. OLE-DB.NET is a .NET layer on top of the OLE layer, so it’s not as fastest and efficient as SqlServer.NET.
20. What is a pre-requisite for connection pooling?
Multiple processes must agree that they will share the same connection, where every parameter is the same, including the security settings. The connection string must be identical.
21. What is Serializatoin?
Serialization is the process of converting an object or a con-nected graph of objects into a contiguous stream of bytes. Deserialization is the process of converting a contiguous stream of bytes back into its graph of connected objects. The ability to convert objects to and from a byte stream is an incredibly useful mechanism. Here are some examples:
o An application's state (object graph) can easily be saved in a disk file or database and then restored the next time the application is run. ASP.NET saves and restores session state by way of serialization and deserialization.
o A set of objects can easily be copied to the system's clipboard and then pasted into the same or another application. In fact, Windows® Forms uses this procedure.
o A set of objects can be cloned and set aside as a backup while a user manipulates the main set of objects.
o A set of objects can easily be sent over the network to a process running on another machine. The Microsoft® .NET Framework remoting architecture serializes and deserializes objects that are marshaled by value.
1. What is ASP.NET?
ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications.
2. How To Repair ASP.Net IIS Mapping After You Remove and Reinstall IIS?
To reassociate aspx file extensions with ASP.Net runtime, you'll have to run the utlity aspnet_regiis.exe -i
3. What are the Best practices for side-by-side execution of Framework 1.0 and 1.1?
In ASP.NET, applications are said to be running side by side when they are installed on the same computer, but use different versions of the .NET Framework.
4. How should I check whether IIS is installed or not?
To verify if IIS is installed, go to your 'Add or Remove Programs' utility in the Control panel and click on the 'Add/Remove Windows Components' in the side menu. On XP Pro and below, you should see an item called "Internet Information Services (IIS)". If this is checked, IIS should be installed. On Win2K3, you'll see "Application Server". If this is checked, select it and then click 'Details'. Another form should open which will contain "Internet Information Services (IIS)". If it is checked, IIS should be installed.
5. In Visual Studio .NET, how do I create a new ASP.NET application for an existing ASP.NET project?
First create an IIS application using the IIS MMC. Then in Visual Studio .NET, use the "New Project In Existing Folder" project template (at the end of the template list). It will first ask you for the project name (use the same one you created for the IIS application). Click OK button. Then enter in physical folder location.
6. In Visual Studio .NET, how do I create a new ASP.NET application which does not have a physical path under wwwroot?
You must first create an IIS application using the IIS MMC. Then in Visual Studio .NET, create a new ASP.NET application and give it the same name you used for the IIS application
7. How to Configure the ASP.NET Version to use for Each Application(developed using 1.1)?
To configure WebApp2 to use ASP.NET 1.1, follow these steps:
1. Click Start, and then click Run.
2. In the Open text box, type cmd, and then click OK.
3. At the command prompt, locate the following directory: WindowsDirectory\Microsoft.NET\Framework\v1.1.4322\
4. At the command prompt, type one of the following commands:
§ To Install ASP.NET 1.1 recursively
aspnet_regiis -s W3SVC/1/ROOT/WebApp2
§ To Install ASP.NET 1.1 non-recursively
aspnet_regiis -sn W3SVC/1/ROOT/WebApp2
8. Can I have VS.NET and the Visual Studio 6.0 installed on the same machine?
Yes! VS.Net works with the .Net framework, while VS6.0 works with MFC or the Windows API directly, for the most part. They can be installed and run on the same machine without any considerations.
9. In Visual Studio .NET, how do I create a new ASP.NET application for an existing ASP.NET project?
First create an IIS application using the IIS MMC. Then in Visual Studio .NET, use the "New Project In Existing Folder" project template (at the end of the template list). It will first ask you for the project name (use the same one you created for the IIS application). Click OK button. Then enter in physical folder location.

1. What is .NET / .NET Framework?
It is a Framework in which Windows applications may be developed and run.
The Microsoft .NET Framework is a platform for building, deploying, and running Web Services and applications. It provides a highly productive, standards-based, multi-language environment for integrating existing investments with next-generation applications and services as well as the agility to solve the challenges of deployment and operation of Internet-scale applications. The .NET Framework consists of three main parts: the common language runtime, a hierarchical set of unified class libraries, and a componentized version of Active Server Pages called ASP.NET.
The .NET Framework provides a new programming model and rich set of classes designed to simplify application development for Windows, the Web, and mobile devices. It provides full support for XML Web services, contains robust security features, and delivers new levels of programming power. The .NET Framework is used by all Microsoft languages including Visual C#, Visual J#, and Visual C++

2. What is "Microsoft Intermediate Language
A .NET programming language (C#, VB.NET, J# etc.) does not compile into executable code; instead it compiles into an intermediate code called Microsoft Intermediate Language (MSIL). As a programmer one need not worry about the syntax of MSIL - since our source code in automatically converted to MSIL. The MSIL code is then send to the CLR (Common Language Runtime) that converts the code to machine language, which is, then run on the host machine. MSIL is similar to Java Byte code.
MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects.
Combined with metadata and the common type system, MSIL allows for true cross- language integration Prior to execution, MSIL is converted to machine code. It is not interpreted

What is "Common Language Runtime
CLR is .NET equivalent of Java Virtual Machine (JVM). It is the runtime that converts a MSIL code into the host machine language code, which is then executed appropriately.
The CLR is the execution engine for .NET Framework applications. It provides a number of services, including:
• Code management (loading and execution)
• Application memory isolation
• Verification of type safety
• Conversion of IL to native code.
• Access to metadata (enhanced type information)
• Managing memory for managed objects
• Enforcement of code access security
• Exception handling, including cross-language exceptions
• Interoperation between managed code, COM objects, and pre-existing DLL's (unmanaged code and data)
• Automation of object layout
• Support for developer services (profiling, debugging, and so on).

it is resource of .net work it functionality is 1.jit(msil to native code)2.garbage collector3.type safety4.multi thread management 5.croossslan exception

What is "Common Language Specification" ...
CLS is the collection of the rules and constraints that every language (that seeks to achieve .NET compatibility) must follow. It is a subsection of CTS and it specifies how it shares and extends one another libraries.

1. What is .NET Framework?
2. Is .NET a runtime service or a development platform? Answer It’s bothand actually a lot more. Microsoft .NET is a company-wide initiative. It includes a new way of delivering software and services to businesses and consumers. A part of Microsoft.NET is the .NET Frameworks. The frameworks is the first part of the MS.NET initiate to ship and it was given out to attendees at the PDC in July. The .NET frameworks consists of two parts: the .NET common language runtime and the .NET class library. These two components are packaged together into the .NET Frameworks SDK which will be available for free download from Microsoft’s MSDN web site later this month. In addition, the SDK also includes command-line compilers for C#, C++, JScript, and VB. You use these compilers to build applications and components. These components require the runtime to execute so this is a development platform. When Visual Studio.NET ships, it will include the .NET SDK and a GUI editor, wizards, tools, and a slew of other things. However, Visual Studio.NET is NOT required to build .NET applications.
3. New features of Framework 1.1 ?
4. What is CLR? How it will work?
5. What is MSIL, IL, CTS?
6. What is JIT and how is works
7. 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.
8. 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
9. Which is the base class for .net Class library? Ans: system.object
10. What is Event? Delegate, clear syntax for writing a event delegate// keyword_delegate.cs // delegate declaration delegate void MyDelegate(int i);
11. class Program
12. {
13. public static void Main()
14. {
15. TakesADelegate(new MyDelegate(DelegateFunction));
16. }
17. public static void TakesADelegate(MyDelegate SomeFunction)
18. {
19. SomeFunction(21);
20. }
21. public static void DelegateFunction(int i)
22. {
23. System.Console.WriteLine("Called by delegate withnumber: {0}.", i);
24. }
25. ment DataGrid in .NET? How would you make a combo-box appear in one column of a DataGrid? What are the ways to show data grid inside a data grid for a master details type of tables?
26. If we write any code for DataGrid methods, what is the access specifier used for that methods in the code behind file and why?
27. What is Application Domain? Application domains provide a unit of isolation for the common language runtime. They are created and run inside a process. Application domains are usually created by a runtime host, which is an application responsible for loading the runtime into a process and executing user code within an application domain. The runtime host creates a process and a default application domain, and runs managed code inside it. Runtime hosts include ASP.NET, Microsoft Internet Explorer, and the Windows shell.
28. What is serialization in .NET? What are the ways to control serialization? 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.
o 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.
o 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.

39. What is the use of trace utility
40. What is different between User Control and Web Control and Custom Control?
41. 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 withtry statements more nested that than the one that caught the exception. Exceptions that occur during destructor execution are worthspecial 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.
42. What is Assembly? Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime withthe information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are a fundamental part of programming withthe .NET Framework. An assembly performs the following functions:
o It contains code that the common language runtime executes. Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is,DllMain,WinMain, orMain).
o It forms asecurity boundary. An assembly is the unit at which permissions are requested and granted.
o It forms atype boundary. Every type’s identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.
o It forms areference scope boundary. The assembly’s manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.
o It forms aversion boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly’s manifest describes the version dependencies you specify for any dependent assemblies.
o It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded.
o It is the unit at which side-by-side execution is supported. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.
There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies withmodules created in other development environments. You can also use common language runtime APIs, such as Reflection.Emit, to create dynamic assemblies.
43. s of assemblies? Private, Public/Shared, Satellite
44. What are Satellite Assemblies? How you will create this? How will you get the different language strings? Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated witha given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies withlocalized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.
45. How will you load dynamic assembly? How will create assemblies at run time?
46. What is Assembly manifest? what all details the assembly manifest will contain. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly’s version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) withMicrosoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies.
47. What are the contents of assembly? In general, a static assembly can consist of four elements:
o The assembly manifest, which contains assembly metadata.
o Type metadata.
o Microsoft intermediate language (MSIL) code that implements the types.
o A set of resources.
48. Difference between assembly manifest & metadata assembly manifest -An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly’s metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. metadata -Information that describes every element managed by the common language runtime: an assembly, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime.
49. What is Global Assembly Cache (GAC) and what is the purpose of it? (How to make an assembly to public? Steps) Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.
50. If I have more than one version of one assemblies, then how’ll I use old version (how/where to specify version number?)in my application?
51. How to find methods of a assembly file (not using ILDASM) Reflection
52. Value type & data types difference. Example from .NET.
53. Integer & struct are value types or reference types in .NET?
54. 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.
55. Readonly vs. const? Aconstfield can only be initialized at the declaration of the field. Areadonlyfield can be initialized either at the declaration or in a constructor. Therefore,readonlyfields can have different values depending on the constructor used. Also, while aconstfield is a compile-time constant, thereadonlyfield can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks;
2. < . { System.Attribute : MyAttribute public attribute.(>
3. < { public this.myvalue="myvalue;" myvalue) MyAttribute(bool constructors(>
4. //Declaring properties
5. public bool MyProperty
6. {
7. get {return this.myvalue;}
8. set {this.myvalue = value;}
9. }
ion 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 ++)
57. C++ & C# differences
58. 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 witha language compiler that targets the runtime is calledmanaged code; itbenefits 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.
59. How do you create threading in .NET? What is the namespace for that?
60. using directive vs using statement You create an instance in ausingstatement to ensure thatDispose is called on the object when theusingstatement is exited. Ausing statement can be exited either when the end of theusingstatement 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.
o Create an alias for a namespace (a using alias).
o Permit the use of types in a namespace, such that, you do not have to qualify the use of a type in that namespace (ausingdirective).
61. Describe the Managed Execution Process
62. What is Active Directory? What is the namespace used to access the Microsoft Active Directories?
63. Interop Services?
64. What is RCW (Run time Callable Wrappers)? The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object.
65. 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.
66. How does you handle this COM components developed in other programming languages in .NET?
67. How will you register com+ services?
68. What is use of ContextUtil class? ContextUtil is the preferred class to use for obtaining COM+ context information.
69. What is the new three features of COM+ services, which are not there in COM (MTS)
70. Is the COM architecture same as .Net architecture? What is the difference between them (if at all there is)?
For more questions and answers, visit Santhosh Thomas’ site, as he constantly updates these questions with answers.

Product Selction Example

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace ViewStateApp

public class WebForm1 : System.Web.UI.Page
protected System.Web.UI.WebControls.Label Label1;
protected System.Web.UI.WebControls.DropDownList ddlPrimary;
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.DropDownList ddlSecondary;
protected System.Web.UI.WebControls.RadioButton rdInclude;
protected System.Web.UI.WebControls.RadioButton rdExclude;
protected System.Web.UI.WebControls.DataGrid DataGrid1;
protected System.Web.UI.WebControls.Button Button1;

private void Page_Load(object sender, System.EventArgs e)
if (!Page.IsPostBack)

private void InitializeComponent()
this.ddlPrimary.SelectedIndexChanged += new System.EventHandler(this.ddlPrimary_SelectedIndexChanged);
this.ddlSecondary.SelectedIndexChanged += new System.EventHandler(this.ddlSecondary_SelectedIndexChanged);
this.Button1.Click += new System.EventHandler(this.Button1_Click);
this.Load += new System.EventHandler(this.Page_Load);

private void PopulateProducts()
ArrayList _ListItems = new ArrayList();
SqlConnection _Con = new SqlConnection("uid=sa;pwd=dev06;server=Dev06;database=winners");
DataSet ds = new DataSet();
SqlCommand _Cmd = new SqlCommand();
_Cmd.Connection = _Con;
_Cmd.CommandType = CommandType.StoredProcedure;
_Cmd.CommandText = "srispddlselect";
SqlDataAdapter da = new SqlDataAdapter(_Cmd);
if (ds != null)
if (ds.Tables[0].Rows.Count > 0)
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
ViewState["ProductName"] = _ListItems;

ddlPrimary.DataSource = _ListItems;
ddlSecondary.DataSource = _ListItems;
ddlPrimary.Items.Insert(0, new ListItem("--SelectOne--", "-1"));
ddlSecondary.Items.Insert(0, new ListItem("--SelectOne--", "-1"));



private void GetProductsToGrid()
SqlConnection _Con = new SqlConnection("uid=sa;pwd=dev06;database=winners;server=Dev06");
SqlCommand _Cmd = new SqlCommand();
DataSet ds = new DataSet();
_Cmd.Connection = _Con;
_Cmd.CommandType = CommandType.StoredProcedure;
_Cmd.CommandText = "SrispGetProductsToGrid";
SqlDataAdapter da = new SqlDataAdapter(_Cmd);
DataGrid1.DataSource = ds;

private void SaveProducts()
string str = "";
SqlConnection _Con = new SqlConnection("uid=sa;pwd=dev06;database=winners;server=Dev06");
SqlCommand _Cmd = new SqlCommand();
_Cmd.Connection = _Con;
_Cmd.CommandType = CommandType.StoredProcedure;
_Cmd.CommandText = "srik_saveproducts";
_Cmd.Parameters.Add("@PrimaryProduct", ddlPrimary.SelectedItem.Text);
_Cmd.Parameters.Add("@SecondaryProduct", ddlSecondary.SelectedItem.Text);
if (rdInclude.Checked)
str = "Include";
str = "Exclude";
_Cmd.Parameters.Add("@Status", str);


private void ddlPrimary_SelectedIndexChanged(object sender, System.EventArgs e)
ArrayList _ListItems=new ArrayList();
ArrayList _Lists=new ArrayList();
string s=ddlPrimary.SelectedItem.Text;
string str=ddlSecondary.SelectedItem.Text;
for(int i=0;i<_Lists.Count;i++)
ddlSecondary.Items.Insert(0,new ListItem("--SelectOne--","-1"));


private void ddlSecondary_SelectedIndexChanged(object sender, System.EventArgs e)
ArrayList _ListItems=new ArrayList();
ArrayList _Lists=new ArrayList();
string s=ddlSecondary.SelectedItem.Text;
string str=ddlPrimary.SelectedItem.Text;
for(int i=0;i<_Lists.Count;i++)
ddlPrimary.Items.Insert(0,new ListItem("--SelectOne--","-1"));


private void Button1_Click(object sender, System.EventArgs e)