Thursday, December 07, 2006

Advanced C# interview questions

1)What’s the advantage of using System.Text.StringBuilder over System.String?

StringBuilder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

Can you store multiple data types in System.Array?

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?

The first one performs a deep copy of the array, the second one is shallow.

How can you sort the elements of the array in descending order?

By calling Sort() and then Reverse() methods.

What’s the .NET datatype that allows the retrieval of data by a unique key?

HashTable.

What’s class SortedList underneath?

A sorted HashTable.

Will finally block get executed if the exception had not occurred?
Yes.

What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?

A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

Can multiple catch blocks be executed?

No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

Why is it a bad idea to throw your own exceptions?

Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block?

Throwing your own exceptions signifies some design flaws in the project.

What’s a delegate?

A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.

What’s a multicast delegate?

It’s a delegate that points to and eventually fires off several methods.

How’s the DLL Hell problem solved in .NET?

Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

What are the ways to deploy an assembly?

An MSI installer, a CAB archive, and XCOPY command.

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.

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

What’s the difference between // comments, /* */ comments and /// comments?

Single-line, multi-line and XML documentation comments.

How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.

What’s the difference between and XML documentation tag?

Single line code example and multiple-line code example.

Is XML case-sensitive?

Yes, so <> and <> are different elements.

What debugging tools come with the .NET SDK?

CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

What does the This window show in the debugger?

It points to the object that’s pointed to by this reference. Object’s instance data is shown.

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.

What’s the difference between the Debug class and Trace class?

Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.

Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from None to Verbose, allowing to fine-tune the tracing activities.

Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

What are three test cases you should go through in unit testing?

Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

Can you change the value of a variable while debugging a C# application?

Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.

Explain the three services model (three-tier application).

Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?

SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

What’s the role of the DataReader class in ADO.NET connections?

It returns a read-only dataset from the data source when the command is executed.

What is the wildcard character in SQL?

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

Explain ACID rule of thumb for transactions.

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

What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

Which one is trusted and which one is untrusted?

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

Why would you use untrusted verificaion?

Web Services might use it, as well as non-Windows applications.

What does the parameter Initial Catalog define inside Connection String?

The database name to connect to.

What’s the data provider name to connect to Access database?

Microsoft.Access.
What does Dispose method do with the connection object? Deletes it from the memory.

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.

ADO.net Interview Questions

Explain what a diffgram is and its usage ?

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

< ?xml version="1.0"? >
< diffgr:diffgram
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"
xmlns:xsd="http://www.w3.org/2001/XMLSchema" >
<>
< /DataInstance >
<>
< /diffgr:before >
<>
< /diffgr:errors >
< /diffgr:diffgram >


The DiffGram format consists of the following blocks of data:

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

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

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

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

You have to use the Fill method of the DataAdapter control and pass the dataset object as an argument to load the generated data.

Can you edit data in the Repeater control?

NO.

Which are the different IsolationLevels ?


Following are the various IsolationLevels:

• Serialized Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. No new data can be inserted that would affect the current transaction. This is the safest isolation level and is the default.


• Repeatable Read Data read by a current transaction cannot be changed by another transaction until the current transaction finishes. Any type of new data can be inserted during a transaction.


• Read Committed A transaction cannot read data that is being modified by another transaction that has not committed. This is the default isolation level in Microsoft® SQL Server.

• Read Uncommitted A transaction can read any data, even if it is being modified by another transaction. This is the least safe isolation level but allows the highest concurrency.

• Any Any isolation level is supported. This setting is most commonly used by downstream components to avoid conflicts. This setting is useful because any downstream component must be configured with an isolation level that is equal to or less than the isolation level of its immediate upstream component. Therefore, a downstream component that has its isolation level configured as Any always uses the same isolation level that its immediate upstream component uses. If the root object in a transaction has its isolation level configured to Any, its isolation level becomes Serialized.

How xml files and be read and write using dataset?

DataSet exposes method like ReadXml and WriteXml to read and write xml

What are the different rowversions available?

There are four types of Rowversions.

Current:

The current values for the row. This row version does not exist for rows with a RowState of Deleted.

Default :

The row the default version for the current DataRowState. For a DataRowState value of Added, Modified or Current, the default version is Current. For a DataRowState of Deleted, the version is Original. For a DataRowState value of Detached, the version is Proposed.

Original:

The row contains its original values.

Proposed:

The proposed values for the row. This row version exists during an edit operation on a row, or for a row that is not part of a DataRowCollection

Explain acid properties?.

The term ACID conveys the role transactions play in mission-critical applications. Coined by transaction processing pioneers, ACID stands for atomicity, consistency, isolation, and durability.
These properties ensure predictable behavior, reinforcing the role of transactions as all-or-none propositions designed to reduce the management load when there are many variables.

Atomicity

A transaction is a unit of work in which a series of operations occur between the BEGIN TRANSACTION and END TRANSACTION statements of an application. A transaction executes exactly once and is atomic — all the work is done or none of it is.
Operations associated with a transaction usually share a common intent and are interdependent. By performing only a subset of these operations, the system could compromise the overall intent of the transaction. Atomicity eliminates the chance of processing a subset of operations.

Consistency

A transaction is a unit of integrity because it preserves the consistency of data, transforming one consistent state of data into another consistent state of data.
Consistency requires that data bound by a transaction be semantically preserved. Some of the responsibility for maintaining consistency falls to the application developer who must make sure that all known integrity constraints are enforced by the application. For example, in developing an application that transfers money, you should avoid arbitrarily moving decimal points during the transfer.

Isolation

A transaction is a unit of isolation — allowing concurrent transactions to behave as though each were the only transaction running in the system.
Isolation requires that each transaction appear to be the only transaction manipulating the data store, even though other transactions may be running at the same time. A transaction should never see the intermediate stages of another transaction.
Transactions attain the highest level of isolation when they are serializable. At this level, the results obtained from a set of concurrent transactions are identical to the results obtained by running each transaction serially. Because a high degree of isolation can limit the number of concurrent transactions, some applications reduce the isolation level in exchange for better throughput.
Durability

A transaction is also a unit of recovery. If a transaction succeeds, the system guarantees that its updates will persist, even if the computer crashes immediately after the commit. Specialized logging allows the system's restart procedure to complete unfinished operations, making the transaction durable.

Whate are different types of Commands available with DataAdapter ?

The SqlDataAdapter has SelectCommand, InsertCommand, DeleteCommand and UpdateCommand

What is a Dataset?

Datasets are the result of bringing together ADO and XML. A dataset contains one or more data of tabular XML, known as DataTables, these data can be treated separately, or can have relationships defined between them. Indeed these relationships give you ADO data SHAPING without needing to master the SHAPE language, which many people are not comfortable with.
The dataset is a disconnected in-memory cache database. The dataset object model looks like this:
Dataset
DataTableCollection
DataTable
DataView
DataRowCollection
DataRow
DataColumnCollection
DataColumn
ChildRelations
ParentRelations
Constraints
PrimaryKey
DataRelationCollection

Let’s take a look at each of these:

DataTableCollection: As we say that a DataSet is an in-memory database. So it has this collection, which holds data from multiple tables in a single DataSet object.

DataTable: In the DataTableCollection, we have DataTable objects, which represents the individual tables of the dataset.

DataView: The way we have views in database, same way we can have DataViews. We can use these DataViews to do Sort, filter data.

DataRowCollection: Similar to DataTableCollection, to represent each row in each Table we have DataRowCollection.

DataRow: To represent each and every row of the DataRowCollection, we have DataRows.

DataColumnCollection: Similar to DataTableCollection, to represent each column in each Table we have DataColumnCollection.

DataColumn: To represent each and every Column of the DataColumnCollection, we have DataColumn.

PrimaryKey: Dataset defines Primary key for the table and the primary key validation will take place without going to the database.

Constraints: We can define various constraints on the Tables, and can use Dataset.Tables(0).enforceConstraints. This will execute all the constraints, whenever we enter data in DataTable.

DataRelationCollection: as we know that we can have more than 1 table in the dataset, we can also define relationship between these tables using this collection and maintain a parent-child relationship.


Explain the ADO . Net Architecture ( .Net Data Provider)

ADO.Net is the data access model for .Net –based applications. It can be used to access relational database systems such as SQL SERVER 2000, Oracle, and many other data sources for which there is an OLD DB or ODBC provider. To a certain extent, ADO.NET represents the latest evolution of ADO technology. However, ADO.NET introduces some major changes and innovations that are aimed at the loosely coupled and inherently disconnected – nature of web applications.
A .Net Framework data provider is used to connecting to a database, executing commands, and retrieving results. Those results are either processed directly, or placed in an ADO.NET DataSet in order to be exposed to the user in an ad-hoc manner, combined with data from multiple sources, or remoted between tiers. The .NET Framework data provider is designed to be lightweight, creating a minimal layer between the data source and your code, increasing performance without sacrificing functionality.

Following are the 4 core objects of .Net Framework Data provider:

• Connection: Establishes a connection to a specific data source
• Command: Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection.
• DataReader: Reads a forward-only, read-only stream of data from a data source.
• DataAdapter: Populates a DataSet and resolves updates with the data source.

The .NET Framework includes the .NET Framework Data Provider for SQL Server (for Microsoft SQL Server version 7.0 or later), the .NET Framework Data Provider for OLE DB, and the .NET Framework Data Provider for ODBC.
The .NET Framework Data Provider for SQL Server: The .NET Framework Data Provider for SQL Server uses its own protocol to communicate with SQL Server. It is lightweight and performs well because it is optimized to access a SQL Server directly without adding an OLE DB or Open Database Connectivity (ODBC) layer. The following illustration contrasts the .NET Framework Data Provider for SQL Server with the .NET Framework Data Provider for OLE DB. The .NET Framework Data Provider for OLE DB communicates to an OLE DB data source through both the OLE DB Service component, which provides connection pooling and transaction services, and the OLE DB Provider for the data source
The .NET Framework Data Provider for OLE DB: The .NET Framework Data Provider for OLE DB uses native OLE DB through COM interoperability to enable data access. The .NET Framework Data Provider for OLE DB supports both local and distributed transactions. For distributed transactions, the .NET Framework Data Provider for OLE DB, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.
The .NET Framework Data Provider for ODBC: The .NET Framework Data Provider for ODBC uses native ODBC Driver Manager (DM) through COM interoperability to enable data access. The ODBC data provider supports both local and distributed transactions. For distributed transactions, the ODBC data provider, by default, automatically enlists in a transaction and obtains transaction details from Windows 2000 Component Services.
The .NET Framework Data Provider for Oracle: The .NET Framework Data Provider for Oracle enables data access to Oracle data sources through Oracle client connectivity software. The data provider supports Oracle client software version 8.1.7 and later. The data provider supports both local and distributed transactions (the data provider automatically enlists in existing distributed transactions, but does not currently support the EnlistDistributedTransaction method).
The .NET Framework Data Provider for Oracle requires that Oracle client software (version 8.1.7 or later) be installed on the system before you can use it to connect to an Oracle data source.
.NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You will need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.

Choosing a .NET Framework Data Provider

.NET Framework Data Provider for SQL Server: Recommended for middle-tier applications using Microsoft SQL Server 7.0 or later. Recommended for single-tier applications using Microsoft Data Engine (MSDE) or Microsoft SQL Server 7.0 or later.
Recommended over use of the OLE DB Provider for SQL Server (SQLOLEDB) with the .NET Framework Data Provider for OLE DB. For Microsoft SQL Server version 6.5 and earlier, you must use the OLE DB Provider for SQL Server with the .NET Framework Data Provider for OLE DB.
.NET Framework Data Provider for OLE DB: Recommended for middle-tier applications using Microsoft SQL Server 6.5 or earlier, or any OLE DB provider. For Microsoft SQL Server 7.0 or later, the .NET Framework Data Provider for SQL Server is recommended. Recommended for single-tier applications using Microsoft Access databases. Use of a Microsoft Access database for a middle-tier application is not recommended.
.NET Framework Data Provider for ODBC: Recommended for middle-tier applications using ODBC data sources. Recommended for single-tier applications using ODBC data sources.
.NET Framework Data Provider for Oracle: Recommended for middle-tier applications using Oracle data sources. Recommended for single-tier applications using Oracle data sources. Supports Oracle client software version 8.1.7 and later. The .NET Framework Data Provider for Oracle classes are located in the System.Data.OracleClient namespace and are contained in the System.Data.OracleClient.dll assembly. You need to reference both the System.Data.dll and the System.Data.OracleClient.dll when compiling an application that uses the data provider.

Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?

Let’s take a look at the differences between ADO Recordset and ADO.Net DataSet:
1. Table Collection: ADO Recordset provides the ability to navigate through a single table of information. That table would have been formed with a join of multiple tables and returning columns from multiple tables. ADO.NET DataSet is capable of holding instances of multiple tables. It has got a Table Collection, which holds multiple tables in it. If the tables are having a relation, then it can be manipulated on a Parent-Child relationship. It has the ability to support multiple tables with keys, constraints and interconnected relationships. With this ability the DataSet can be considered as a small, in-memory relational database cache.
2. Navigation: Navigation in ADO Recordset is based on the cursor mode. Even though it is specified to be a client-side Recordset, still the navigation pointer will move from one location to another on cursor model only. ADO.NET DataSet is an entirely offline, in-memory, and cache of data. All of its data is available all the time. At any time, we can retrieve any row or column, constraints or relation simply by accessing it either ordinarily or by retrieving it from a name-based collection.
3. Connectivity Model: The ADO Recordset was originally designed without the ability to operate in a disconnected environment. ADO.NET DataSet is specifically designed to be a disconnected in-memory database. ADO.NET DataSet follows a pure disconnected connectivity model and this gives it much more scalability and versatility in the amount of things it can do and how easily it can do that.
4. Marshalling and Serialization: In COM, through Marshalling, we can pass data from 1 COM component to another component at any time. Marshalling involves copying and processing data so that a complex type can appear to the receiving component the same as it appeared to the sending component. Marshalling is an expensive operation. ADO.NET Dataset and DataTable components support Remoting in the form of XML serialization. Rather than doing expensive Marshalling, it uses XML and sent data across boundaries.
5. Firewalls and DCOM and Remoting: Those who have worked with DCOM know that how difficult it is to marshal a DCOM component across a router. People generally came up with workarounds to solve this issue. ADO.NET DataSet uses Remoting, through which a DataSet / DataTable component can be serialized into XML, sent across the wire to a new AppDomain, and then Desterilized back to a fully functional DataSet. As the DataSet is completely disconnected, and it has no dependency, we lose absolutely nothing by serializing and transferring it through Remoting.

How do you handle data concurrency in .NET ?

One of the key features of the ADO.NET DataSet is that it can be a self-contained and disconnected data store. It can contain the schema and data from several rowsets in DataTable objects as well as information about how to relate the DataTable objects-all in memory. The DataSet neither knows nor cares where the data came from, nor does it need a link to an underlying data source. Because it is data source agnostic you can pass the DataSet around networks or even serialize it to XML and pass it across the Internet without losing any of its features. However, in a disconnected model, concurrency obviously becomes a much bigger problem than it is in a connected model.
In this column, I'll explore how ADO.NET is equipped to detect and handle concurrency violations. I'll begin by discussing scenarios in which concurrency violations can occur using the ADO.NET disconnected model. Then I will walk through an ASP.NET application that handles concurrency violations by giving the user the choice to overwrite the changes or to refresh the out-of-sync data and begin editing again. Because part of managing an optimistic concurrency model can involve keeping a timestamp (rowversion) or another type of flag that indicates when a row was last updated, I will show how to implement this type of flag and how to maintain its value after each database update.

Is Your Glass Half Full?

There are three common techniques for managing what happens when users try to modify the same data at the same time: pessimistic, optimistic, and last-in wins. They each handle concurrency issues differently.
The pessimistic approach says: "Nobody can cause a concurrency violation with my data if I do not let them get at the data while I have it." This tactic prevents concurrency in the first place but it limits scalability because it prevents all concurrent access. Pessimistic concurrency generally locks a row from the time it is retrieved until the time updates are flushed to the database. Since this requires a connection to remain open during the entire process, pessimistic concurrency cannot successfully be implemented in a disconnected model like the ADO.NET DataSet, which opens a connection only long enough to populate the DataSet then releases and closes, so a database lock cannot be held.
Another technique for dealing with concurrency is the last-in wins approach. This model is pretty straightforward and easy to implement-whatever data modification was made last is what gets written to the database. To implement this technique you only need to put the primary key fields of the row in the UPDATE statement's WHERE clause. No matter what is changed, the UPDATE statement will overwrite the changes with its own changes since all it is looking for is the row that matches the primary key values. Unlike the pessimistic model, the last-in wins approach allows users to read the data while it is being edited on screen. However, problems can occur when users try to modify the same data at the same time because users can overwrite each other's changes without being notified of the collision. The last-in wins approach does not detect or notify the user of violations because it does not care. However the optimistic technique does detect violations. Contd....

In optimistic concurrency models, a row is only locked during the update to the database. Therefore the data can be retrieved and updated by other users at any time other than during the actual row update operation. Optimistic concurrency allows the data to be read simultaneously by multiple users and blocks other users less often than its pessimistic counterpart, making it a good choice for ADO.NET. In optimistic models, it is important to implement some type of concurrency violation detection that will catch any additional attempt to modify records that have already been modified but not committed. You can write your code to handle the violation by always rejecting and canceling the change request or by overwriting the request based on some business rules. Another way to handle the concurrency violation is to let the user decide what to do. The sample application that is shown in Figure 1 illustrates some of the options that can be presented to the user in the event of a concurrency violation.

Where Did My Changes Go?

When users are likely to overwrite each other's changes, control mechanisms should be put in place. Otherwise, changes could be lost. If the technique you're using is the last-in wins approach, then these types of overwrites are entirely possible.For example, imagine Julie wants to edit an employee's last name to correct the spelling. She navigates to a screen which loads the employee's information into a DataSet and has it presented to her in a Web page. Meanwhile, Scott is notified that the same employee's phone extension has changed. While Julie is correcting the employee's last name, Scott begins to correct his extension. Julie saves her changes first and then Scott saves his.Assuming that the application uses the last-in wins approach and updates the row using a SQL WHERE clause containing only the primary key's value, and assuming a change to one column requires the entire row to be updated, neither Julie nor Scott may immediatelyrealize the concurrency issue that just occurred. In this particular situation, Julie's changes were overwritten by Scott's changes because he saved last, and the last name reverted to the misspelled version.
So as you can see, even though the users changed different fields, their changes collided and caused Julie's changes to be lost. Without some sort of concurrency detection and handling, these types of overwrites can occur and even go unnoticed.When you run the sample application included in this column's download, you should open two separate instances of Microsoft® Internet Explorer. When I generated the conflict, I opened two instances to simulate two users with two separate sessions so that a concurrency violation would occur in the sample application. When you do this, be careful not to use Ctrl+N because if you open one instance and then use the Ctrl+N technique to open another instance, both windows will share the same session.

Detecting Violations

The concurrency violation reported to the user in Figure 1 demonstrates what can happen when multiple users edit the same data at the same time. In Figure 1, the user attempted to modify the first name to "Joe" but since someone else had already modified the last name to "Fuller III," a concurrency violation was detected and reported. ADO.NET detects a concurrency violation when a DataSet containing changed values is passed to a SqlDataAdapter's Update method and no rows are actually modified. Simply using the primary key (in this case the EmployeeID) in the UPDATE statement's WHERE clause will not cause a violation to be detected because it still updates the row (in fact, this technique has the same outcome as the last-in wins technique). Instead, more conditions must be specified in the WHERE clause in order for ADO.NET to detect the violation.
The key here is to make the WHERE clause explicit enough so that it not only checks the primary key but that it also checks for another appropriate condition. One way to accomplish this is to pass in all modifiable fields to the WHERE clause in addition to the primary key. For example, the application shown in Figure 1 could have its UPDATE statement look like the stored procedure that's shown in Figure 2.
Notice that in the code in Figure 2 nullable columns are also checked to see if the value passed in is NULL. This technique is not only messy but it can be difficult to maintain by hand and it requires you to test for a significant number of WHERE conditions just to update a row. This yields the desired result of only updating rows where none of the values have changed since the last time the user got the data, but there are other techniques that do not require such a huge WHERE clause.
Another way to make sure that the row is only updated if it has not been modified by another user since you got the data is to add a timestamp column to the table. The SQL Server(tm) TIMESTAMP datatype automatically updates itself with a new value every time a value in its row is modified. This makes it a very simple and convenient tool to help detect concurrency violations.
A third technique is to use a DATETIME column in which to track changes to its row. In my sample application I added a column called LastUpdateDateTime to the Employees table.

ALTER TABLE Employees ADD LastUpdateDateTime DATETIME

There I update the value of the LastUpdateDateTime field automatically in the UPDATE stored procedure using the built-in SQL Server GETDATE function.
The binary TIMESTAMP column is simple to create and use since it automatically regenerates its value each time its row is modified, but since the DATETIME column technique is easier to display on screen and demonstrate when the change was made, I chose it for my sample application. Both of these are solid choices, but I prefer the TIMESTAMP technique since it does not involve any additional code to update its value.

Retrieving Row Flags

One of the keys to implementing concurrency controls is to update the timestamp or datetime field's value back into the DataSet. If the same user wants to make more modifications, this updated value is reflected in the DataSet so it can be used again. There are a few different ways to do this. The fastest is using output parameters within the stored procedure. (This should only return if @@ROWCOUNT equals 1.) The next fastest involves selecting the row again after the UPDATE within the stored procedure. The slowest involves selecting the row from another SQL statement or stored procedure from the SqlDataAdapter's RowUpdated event.
I prefer to use the output parameter technique since it is the fastest and incurs the least overhead. Using the RowUpdated event works well, but it requires me to make a second call from the application to the database. The following code snippet adds an output parameter to the SqlCommand object that is used to update the Employee information:
oUpdCmd.Parameters.Add(new SqlParameter("@NewLastUpdateDateTime",
SqlDbType.DateTime, 8, ParameterDirection.Output,
false, 0, 0, "LastUpdateDateTime", DataRowVersion.Current, null));
oUpdCmd.UpdatedRowSource = UpdateRowSource.OutputParameters;
The output parameter has its sourcecolumn and sourceversion arguments set to point the output parameter's return value back to the current value of the LastUpdateDateTime column of the DataSet. This way the updated DATETIME value is retrieved and can be returned to the user's .aspx page. Contd....


Saving Changes

Now that the Employees table has the tracking field (LastUpdateDateTime) and the stored procedure has been created to use both the primary key and the tracking field in the WHERE clause of the UPDATE statement, let's take a look at the role of ADO.NET. In order to trap the event when the user changes the values in the textboxes, I created an event handler for the TextChanged event for each TextBox control:
private void txtLastName_TextChanged(object sender, System.EventArgs e)
{
// Get the employee DataRow (there is only 1 row, otherwise I could
// do a Find)
dsEmployee.EmployeeRow oEmpRow =
(dsEmployee.EmployeeRow)oDsEmployee.Employee.Rows[0];
oEmpRow.LastName = txtLastName.Text;
// Save changes back to Session
Session["oDsEmployee"] = oDsEmployee;
}

This event retrieves the row and sets the appropriate field's value from the TextBox. (Another way of getting the changed values is to grab them when the user clicks the Save button.) Each TextChanged event executes after the Page_Load event fires on a postback, so assuming the user changed the first and last names, when the user clicks the Save button, the events could fire in this order: Page_Load, txtFirstName_TextChanged, txtLastName_TextChanged, and btnSave_Click.
The Page_Load event grabs the row from the DataSet in the Session object; the TextChanged events update the DataRow with the new values; and the btnSave_Click event attempts to save the record to the database. The btnSave_Click event calls the SaveEmployee method (shown in Figure 3) and passes it a bLastInWins value of false since we want to attempt a standard save first. If the SaveEmployee method detects that changes were made to the row (using the HasChanges method on the DataSet, or alternatively using the RowState property on the row), it creates an instance of the Employee class and passes the DataSet to its SaveEmployee method. The Employee class could live in a logical or physical middle tier. (I wanted to make this a separate class so it would be easy to pull the code out and separate it from the presentation logic.)
Notice that I did not use the GetChanges method to pull out only the modified rows and pass them to the Employee object's Save method. I skipped this step here since there is only one row. However, if there were multiple rows in the DataSet's DataTable, it would be better to use the GetChanges method to create a DataSet that contains only the modified rows.
If the save succeeds, the Employee.SaveEmployee method returns a DataSet containing the modified row and its newly updated row version flag (in this case, the LastUpdateDateTime field's value). This DataSet is then merged into the original DataSet so that the LastUpdateDateTime field's value can be updated in the original DataSet. This must be done because if the user wants to make more changes she will need the current values from the database merged back into the local DataSet and shown on screen. This includes the LastUpdateDateTime value which is used in the WHERE clause. Without this field's current value, a false concurrency violation would occur.

Reporting Violations

If a concurrency violation occurs, it will bubble up and be caught by the exception handler shown in Figure 3 in the catch block for DBConcurrencyException. This block calls the FillConcurrencyValues method, which displays both the original values in the DataSet that were attempted to be saved to the database and the values currently in the database. This method is used merely to show the user why the violation occurred. Notice that the exDBC variable is passed to the FillConcurrencyValues method. This instance of the special database concurrency exception class (DBConcurrencyException) contains the row where the violation occurred. When a concurrency violation occurs, the screen is updated to look like Figure 1.
The DataSet not only stores the schema and the current data, it also tracks changes that have been made to its data. It knows which rows and columns have been modified and it keeps track of the before and after versions of these values. When accessing a column's value via the DataRow's indexer, in addition to the column index you can also specify a value using the DataRowVersion enumerator. For example, after a user changes the value of the last name of an employee, the following lines of C# code will retrieve the original and current values stored in the LastName column:

string sLastName_Before = oEmpRow["LastName", DataRowVersion.Original];
string sLastName_After = oEmpRow["LastName", DataRowVersion.Current];

The FillConcurrencyValues method uses the row from the DBConcurrencyException and gets a fresh copy of the same row from the database. It then displays the values using the DataRowVersion enumerators to show the original value of the row before the update and the value in the database alongside the current values in the textboxes.

User's Choice

Once the user has been notified of the concurrency issue, you could leave it up to her to decide how to handle it. Another alternative is to code a specific way to deal with concurrency, such as always handling the exception to let the user know (but refreshing the data from the database). In this sample application I let the user decide what to do next. She can either cancel changes, cancel and reload from the database, save changes, or save anyway.
The option to cancel changes simply calls the RejectChanges method of the DataSet and rebinds the DataSet to the controls in the ASP.NET page. The RejectChanges method reverts the changes that the user made back to its original state by setting all of the current field values to the original field values. The option to cancel changes and reload the data from the database also rejects the changes but additionally goes back to the database via the Employee class in order to get a fresh copy of the data before rebinding to the control on the ASP.NET page.
The option to save changes attempts to save the changes but will fail if a concurrency violation is encountered. Finally, I included a "save anyway" option. This option takes the values the user attempted to save and uses the last-in wins technique, overwriting whatever is in the database. It does this by calling a different command object associated with a stored procedure that only uses the primary key field (EmployeeID) in the WHERE clause of the UPDATE statement. This technique should be used with caution as it will overwrite the record.
If you want a more automatic way of dealing with the changes, you could get a fresh copy from the database. Then overwrite just the fields that the current user modified, such as the Extension field. That way, in the example I used the proper LastName would not be overwritten. Use this with caution as well, however, because if the same field was modified by both users, you may want to just back out or ask the user what to do next. What is obvious here is that there are several ways to deal with concurrency violations, each of which must be carefully weighed before you decide on the one you will use in your application.

Wrapping It Up

Setting the SqlDataAdapter's ContinueUpdateOnError property tells the SqlDataAdapter to either throw an exception when a concurrency violation occurs or to skip the row that caused the violation and to continue with the remaining updates. By setting this property to false (its default value), it will throw an exception when it encounters a concurrency violation. This technique is ideal when only saving a single row or when you are attempting to save multiple rows and want them all to commit or all to fail.
I have split the topic of concurrency violation management into two parts. Next time I will focus on what to do when multiple rows could cause concurrency violations. I will also discuss how the DataViewRowState enumerators can be used to show what changes have been made to a DataSet.

How you will set the datarelation between two columns?

ADO.NET provides DataRelation object to set relation between two columns.It helps to enforce the following constraints,a unique constraint, which guarantees that a column in the table contains no duplicates and a foreign-key constraint,which can be used to maintain referential integrity.A unique constraint is implemented either by simply setting the Unique property of a data column to true, or by adding an instance of the UniqueConstraint class to the DataRelation object's ParentKeyConstraint. As part of the foreign-key constraint, you can specify referential integrity rules that are applied at three points,when a parent record is updated,when a parent record is deleted and when a change is accepted or rejected.

Sunday, November 26, 2006

C# Interview Questions

1.What’s the implicit name of the parameter that gets passed into the class’ set method?

Value and its data type depend on whatever variable we’re changing.

2.How do you inherit from a class in C#?

Place a colon and then the name of the base class. Notice that it’s double colon in C++.

3.Does C# support multiple inheritances?

No, use interfaces instead.

4.When you inherit a protected class-level variable, who is it available to?

Classes in the same namespace.

5.Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

6.Describe the accessibility modifier protected internal.

It’s available to derived classes and classes within the same Assembly (and naturally from the base class it’s declared in).

7.C# provides a default constructor for me. I write a constructor that takes a string as a parameter, but want to keep the no parameter one. How many constructors should I write?

Two. Once you write at least one constructor, C# cancels the freebie constructor, and now you have to write one yourself, even if there’s no implementation in it.

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

System. Object.

9.How’s method overriding different from overloading?

When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

10.What does the keyword virtual mean in the method definition?

The method can be over-ridden.

11.Can you declare the override method static while the original method is non-static?

No, you can’t, the signature of the virtual method must remain the same, only the keyword virtual is changed to keyword override.

12.Can you override private virtual methods?

No, moreover, you cannot access private methods in inherited classes, have to be protected in the base class to allow any sort of access.

13.Can you prevent your class from being inherited and becoming a base class for some other classes?

Yes, that’s what keyword sealed in the class definition is for. The developer trying to derive from your class will get a message: cannot inherit from Sealed class WhateverBaseClassName. It’s the same concept as final class in Java.

14.Can you allow class to be inherited, but prevent the method from being over-ridden?

Yes, just leave the class public and make the method sealed.

15.What’s an abstract class?

A class that cannot be instantiated. A concept in C++ known as pure virtual method. A class that must be inherited and have the methods over-ridden. Essentially, it’s a blueprint for a class without any implementation.

16.When do you absolutely have to declare a class as abstract (as opposed to free-willed educated choice or decision based on UML diagram)?

When at least one of the methods in the class is abstract. When the class itself is inherited from an abstract class, but not all base abstract methods have been over-ridden.

17.What’s an interface class?

It’s an abstract class with public abstract methods all of which must be implemented in the inherited classes.

18.Why can’t you specify the accessibility modifier for methods inside the interface?

They all must be public. Therefore, to prevent you from getting the false impression that you have any freedom of choice, you are not allowed to specify any accessibility, its public by default.

19.Can you inherit multiple interfaces?

Yes, why not.

20.And if they have conflicting method names?

It’s up to you to implement the method inside your own class, so implementation is left entirely up to you. This might cause a problem on a higher-level scale if similarly named methods from different interfaces expect different data, but as far as compiler cares you’re okay.

21.What’s the difference between an interface and abstract class?

In the interface all methods must be abstract; in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes.

22.How can you overload a method?

Different parameter data types, different number of parameters, different order of parameters.

23.If a base class has a bunch of overloaded constructors, and an inherited class has another bunch of overloaded constructors, can you enforce a call from an inherited constructor to an arbitrary base constructor?

Yes, just place a colon, and then keyword base (parameter list to invoke the appropriate constructor) in the overloaded constructor definition inside the inherited class.

24.What’s the difference between Systems? String and System.StringBuilder classes?

System. String is immutable; System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

25.What’s the advantage of using System.Text.StringBuilder over System? String?

String Builder is more efficient in the cases, where a lot of manipulation is done to the text. Strings are immutable, so each time it’s being operated on, a new instance is created.

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

No.

27.What’s the difference between the System.Array.CopyTo () and System.Array.Clone ()?

The first one performs a deep copy of the array, the second one is shallow.

28.How can you sort the elements of the array in descending order?

By calling Sort () and then Reverse () methods.

29.What’s the .NET data type that allows the retrieval of data by a unique key?

Hash Table.

30.What’s class Sorted List underneath?

A sorted Hash Table.

31.Will finally block get executed if the exception had not occurred?

Yes.

32. What’s the C# equivalent of C++ catch (…), which was a catch-all statement for any possible exception?

A catch block that catches the exception of type System. Exception. You can also omit the parameter data type in this case and just write catch {}.

33.Can multiple catch blocks be executed?

No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block.

34.Why is it a bad idea to throw your own exceptions?

Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

35.What’s a delegate?

A delegate object encapsulates a reference to a method. In C++ they were referred to as function pointers.
36.What’s a multicast delegate?

It’s a delegate that points to and eventually fires off several methods.

37.How’s the DLL Hell problem solved in .NET?

Assembly versioning allows the application to specify not only the library it needs to run (which was available under Win32), but also the version of the assembly.

38.What are the ways to deploy an assembly?

An MSI installer, a CAB archive, and XCOPY command.

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

40.What namespaces are necessary to create a localized application?

System. Globalization, System. Resources.

41.What’s the difference between // comments, /* */ comments and /// comments?

Single-line, multi-line and XML documentation comments.

42.How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.

43.What’s the difference between and XML documentation tag?

Single line code example and multiple-line code example.

44.Is XML case-sensitive?

Yes, so and are different elements.

45.What debugging tools come with the .NET SDK?

CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.

46.What does the window show in the debugger?

It points to the object that’s pointed to by this reference. Object’s instance data is shown.

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

48.What’s the difference between the Debug class and Trace class? Documentation looks the same.

Use Debug class for debug builds, use Trace class for both debug and release builds.

49.Why are there five tracing levels in System.Diagnostics.TraceSwitcher?

The tracing dumps can be quite verbose and for some applications that are constantly running you run the risk of overloading the machine and the hard drive there. Five levels range from none to Verbose, allowing fine-tuning the tracing activities.

50.Where is the output of TextWriterTraceListener redirected?

To the Console or a text file depending on the parameter passed to the constructor.

51.How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.

52.What are three test cases you should go through in unit testing?

Positive test cases (correct data, correct output), negative test cases (broken or missing data, proper handling), exception test cases (exceptions are thrown and caught properly).

53.Can you change the value of a variable while debugging a C# application?

Yes, if you are debugging via Visual Studio.NET, just go to immediate window.

54.Explain the three services model (three-tier application).

Presentation (UI), business (logic and underlying code) and data (from storage or other sources).

55.What are advantages and disadvantages of Microsoft-provided data provider classes in ADO.NET?

SQLServer.NET data provider is high-speed and robust, but requires SQL Server license purchased from Microsoft. OLE-DB.NET is universal for accessing other sources, like Oracle, DB2, Microsoft Access and Informix, but it’s a .NET layer on top of OLE layer, so not the fastest thing in the world. ODBC.NET is a deprecated layer provided for backward compatibility to ODBC engines.

56.What’s the role of the Data Reader class in ADO.NET connections?

It returns a read-only dataset from the data source when the command is executed.

57.What is the wildcard character in SQL? Let’s say you want to query database with LIKE for all employees whose name starts with La.

The wildcard character is %, the proper query with LIKE would involve ‘La%’.

58.Explain ACID rule of thumb for transactions.

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

59.What connections does Microsoft SQL Server support?

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords).

60.Which one is trusted and which one is untrusted?

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

61.Why would you use untrusted verification?

Web Services might use it, as well as non-Windows applications.

62.What does the parameter Initial Catalog define inside Connection String?

The database name to connect to.

63.What’s the data provider name to connect to Access database?

Microsoft. Access.

64.What does dispose method do with the connection object?

Deletes it from the memory.

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

.NET deployment questions

1. What do you know about .NET assemblies?

Assemblies are the smallest units of versioning and deployment in the .NET application. Assemblies are also the building blocks for programs such as Web services, Windows services, serviced components, and .NET remoting applications.

2. What’s the difference between private and shared assembly?

Private assembly is used inside an application only and does not have to be identified by a strong name. Shared assembly can be used by multiple applications and has to have a strong name.

3. What’s a strong name?

A strong name includes the name of the assembly, version number, culture identity, and a public key token.

4. How can you tell the application to look for assemblies at the locations other than its own install?

Use the directive in the XML .config file for a given application.

should do the trick. Or you can add additional search paths in the Properties box of the deployed application.

5. How can you debug failed assembly binds?

Use the Assembly Binding Log Viewer (fuslogvw.exe) to find out the paths searched.

6. Where are shared assemblies stored?

Global assembly cache.

7. How can you create a strong name for a .NET assembly?

With the help of Strong Name tool (sn.exe).

8. Where’s global assembly cache located on the system?

Usually C:\winnt\assembly or C:\windows\assembly.

9. Can you have two files with the same file name in GAC?

Yes, remember that GAC is a very special folder, and while normally you would not be able to place two files with the same name into a Windows folder, GAC differentiates by version number as well, so it’s possible for MyApp.dll and MyApp.dll to co-exist in GAC if the first one is version 1.0.0.0 and the second one is 1.1.0.0.

10. So let’s say I have an application that uses MyApp.dll assembly, version 1.0.0.0. There is a security bug in that assembly, and I publish the patch, issuing it under name MyApp.dll 1.1.0.0. How do I tell the client applications that are already installed to start using this new MyApp.dll?

Use publisher policy. To configure a publisher policy, use the publisher policy configuration file, which uses a format similar app .config file. But unlike the app .config file, a publisher policy file needs to be compiled into an assembly and placed in the GAC.

11. What is delay signing?

Delay signing allows you to place a shared assembly in the GAC by signing the assembly with just the public key. This allows the assembly to be signed with the private key at a later stage, when the development process is complete and the component or assembly is ready to be deployed. This process enables developers to work with shared assemblies as if they were strongly named, and it secures the private key of the signature from being accessed at different stages of development.

Saturday, November 25, 2006

ASP. NET Interview Questions

ASP. NET Interview Questions


Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

inetinfo.exe is the Microsoft IIS server running, handling ASP. NET requests among other things. When an ASP. NET request is received (usually a file with .aspx extension), the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.

What’s the difference between Response. Write() and Response. Output. Write()?

Response.Output.Write() allows you to write formatted output.

What methods are fired during the page load?

Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.

When during the page processing cycle is View State available?

After the Init() and before the Page_Load(), or OnLoad() for a control.

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

System.Web.UI.Page

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

System.Web.UI.Page.Culture

What’s the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?

Code Behind is relevant to Visual Studio.NET only.

What’s a bubbled event?

When you have a complex control, like Data Grid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main Data Grid event handler to take care of its constituents.

Suppose you want a certain ASP. NET function executed on Mouse Over for a certain button. Where do you add an event handler?

Add an OnMouseOver attribute to the button.
Example: btnSubmit.Attributes.Add("onmouseover","someClientCodeHere();");

What data types do the RangeValidator control support?

Integer, String, and Date.

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

Server-side code executes on the server. Client-side code executes in the client's browser.

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

The answer is server-side code since code-behind is executed on the server. However, during the code-behind's execution on the server, it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.

Should user input data validation occur server-side or client-side? Why?

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

What is the difference between Server. Transfer and Response. Redirect? Why would I choose one over the other?

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

Can you explain the difference between an ADO. NET Dataset and an ADO Record set?

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

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.

What are the Application_Start and Session_Start subroutines used for?

This is where you can set the specific variables for the Application and Session objects.

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

When you want to inherit (use the functionality of) another class. Example: With a base class named Employee, a Manager class could be derived from the Employee base class.

Whats an assembly?

Assemblies are the building blocks of the .NET framework. Overview of assemblies from MSDN

Describe the difference between inline and code behind.

Inline code written along side the html in a page. Code-behind is code written in a separate file and referenced by the .aspx page.

Explain what a diffgram is, and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. A good use is reading database data to an XML file to be sent to a Web Service.

Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.

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

The Fill() method.

Can you edit data in the Repeater control?

No, it just reads the information from its data source.

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

ItemTemplate.

How can you provide an alternating color scheme in a Repeater control?

Use the AlternatingItemTemplate.

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

You must set the DataSource property and call the DataBind method.

What base class do all Web Forms inherit from?

The Page class.

Name two properties common in every validation control?

ControlToValidate property and Text property.

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

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

CompareValidator control.

How many classes can a single .NET DLL contain?

It can contain many classes.

True or False: A Web service can only be written in .NET?

False

What does WSDL stand for?

Web Services Description Language

Where on the Internet would you look for Web services?

http://www.uddi.org

Which property on a Combo Box do you set with a column name, prior to setting the Data Source, to display data in the combo box?

DataTextField property

True or False: To test a Web service you must create a windows application or Web application to consume this service?

False, the web service comes with a test page and it provides HTTP-GET method to test.

What is the transport protocol you use to call a Web service?

SOAP (Simple Object Access Protocol) is the preferred protocol.

True or False: To test a Web service you must create a Windows application or Web application to consume this service?

False, the web service comes with a test page and it provides HTTP-GET method to test.


State Management Questions


What is View State?

View State allows the state of objects (serializable) to be stored in a hidden field on the page. View State is transported to the client and back to the server, and is not stored on the server or any other external source. View State is used the retain the state of server-side objects between postabacks.

What is the lifespan for items stored in View State?

Item stored in View State exist for the life of the current page. This includes post backs (to the same page).

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

It allows the page to save the users input on a form across post backs. It saves the server-side values for a given control into View State, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in view state.

What are the different types of Session state management options available with ASP. NET?

ASP. NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

Explain the code behind wors and contrast that using the inline style.

Different types of HTML,Web and server controls (also how Server control validation controls work)

Difference btn user and server controls

Server controls are built-in. User controls are created by the developer to allow for the reuse of controls that need specific functionality.

How server form post-back works (perhaps ask about view state as well).

By default all pages in .NET post back to themselves. The view state keeps the users input updated on the page.

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

No, You have to use Server. Transfer to pass the data to another page.

What is the role of global.asax.

Store global information about the application

How would ASP and ASP. NET apps run at the same time on the same server?

What are good ADO. NET object's) to replace the ADO Record set object.

What is view state and use of it?

The current property settings of an ASP. NET page and those of any ASP. NET server controls contained within the page. ASP. NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly.

What are user controls and custom controls?

Custom controls: A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP. NET pages). A custom client control is used in Windows Forms applications.

User Controls: In ASP. NET: A user-authored server control that enables an ASP. NET page to be re-used as a server control. An ASP. NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP. NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.


What are the validation controls?

A set of server controls included with ASP. NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script

What's the difference between Response. Write() and Response.Output.Write()?

The latter one allows you to write formatted output

Where does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page

Where do you store the information about the user's locale?

System.Web.UI.Page.Culture

What's the difference between Code behind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"? Code Behind is relevant to Visual Studio.NET only.

What's a bubbled event?

When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button, row, etc.) is quite tedious. The controls can bubble up their event handlers, allowing the main Data Grid event handler to take care of its constituents. Suppose you want a certain ASP. NET function executed on Mouse Over over a certain button.

Where do you add an event handler?

It's the Attributes property, the Add function inside that property. e.g. btnSubmit.Attributes.Add("onMouseOver","some Client Code();")

What data type does the RangeValidator control support?

Integer, String and Date.

Describe the difference between a Thread and a Process?

Thread - is used to execute more than one program at a time.

process - executes single program

What is a Windows Service and how does its lifecycle differ from a “standard” EXE?

Windows Service applications are long-running applications that are ideal for use in server environments. The applications do not have a user interface or produce any visual output; it is instead used by other programs or the system to perform operations. Any user messages are typically written to the Windows Event Log. Services can be automatically started when the computer is booted. This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. They do not require a logged in user in order to execute and can run under the context of any user including the system. Windows Services are controlled through the Service Control Manager where they can be stopped, paused, and started as needed.

How does the lifecycle of Windows services differ from Standard EXE?

Windows services lifecycle is managed by “Service Control Manager” which is responsible for starting and stopping the service and the applications do not have a user interface or produce any visual output, but “Standard executable” doesn’t require Control Manager and is directly related to the visual output

What is the difference between a.Equals(b) and a == b?

a == b is used to compare the references of two objects

a.Equals(b) is used to compare two objects

What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?

What is the difference between an EXE and a DLL?

An EXE can run independently, whereas DLL will run within an EXE. DLL is an in-process file and EXE is an out-process file

What is strong-typing versus weak-typing? Which is preferred? Why?

Strong type is checking the types of variables as soon as possible, usually at compile time. While weak typing is delaying checking the types of the system as late as possible, usually to run-time. Which is preferred depends on what you want. For scripts & quick stuff you’ll usually want weak typing, because you want to write as much less (is this a correct way to use Ensligh?) code as possible. In big programs, strong typing can reduce errors at compile time.

What’s wrong with a line like this? DateTime.Parse(myString)

the result returned by this function is not assigned to anything, should be something like
varx = DateTime.Parse(myString)

What are PDBs? Where must they be located for debugging to work?

A program database (PDB) file holds debugging and project state information that allows incremental linking of a Debug configuration of your program.

The linker creates project.PDB, which contains debug information for the project’s EXE file. The project.PDB contains full debug information, including function prototypes, not just the type information found in VCx0.PDB. Both PDB files allow incremental updates.

They should be located at bin\Debug directory

To debug precompiled components such as business objects and code-behind modules, you need to generate debug symbols. To do this, compile the components with the debug flags by using either Visual Studio .NET or a command line compiler such as Csc.exe (for Microsoft Visual C# .NET) or Vbc.exe (for Microsoft Visual Visual Basic .NET).

Using Visual Studio .NET1. Open the ASP. NET Web Application project in Visual Studio .NET.
2. Right-click the project in the Solution Explorer and click Properties.
3. In the Properties dialog box, click the Configuration Properties folder.
4. In the left pane, select Build.
5. Set Generate Debugging Information to true.
6. Close the Properties dialog box.
7. Right-click the project and click Build to compile the project and generate symbols (.pdb files).
What is cyclomatic complexity and why is it important?

Cyclomatic complexity is a computer science metric (measurement) developed by Thomas McCabe used to generally measure the complexity of a program. It directly measures the number of linearly independent paths through a program’s source code.

The concept, although not the method, is somewhat similiar to that of general text complexity measured by the Flesch-Kincaid Readability Test.

Cyclomatic complexity is computed using a graph that describes the control flow of the program. The nodes of the graph correspond to the commands of a program. A directed edge connects two nodes, if the second command might be executed immediately after the first command. By definition,

CC = E - N + P

where
CC = cyclomatic complexity
E = the number of edges of the graph
N = the number of nodes of the graph
P = the number of connected components.

Write a standard lock() plus double check to create a critical section around a variable access.


What is FullTrust? Do GAC’ed assemblies have FullTrust?

Your code is allowed to do anything in the framework, meaning that all (.Net) permissions are granted. The GAC has FullTrust because it’s on the local HD, and that has FullTrust by default, you can change that using caspol


What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

What does this do? gacutil /l | find /i “about”

This command is used to install strong typed assembly in GAC

What does this do? sn -t foo.dll

What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

Contrast OOP and SOA. What are tenets of each

Service Oriented Architecture. In SOA you create an abstract layer that your applications use to access various “services” and can aggregate the services. These services could be databases, web services, message queues or other sources. The Service Layer provides a way to access these services that the applications do not need to know how the access is done. For example, to get a full customer record, I might need to get data from a SGL Server database, a web service and a message queue. The Service layer hides this from the calling application. All the application knows is that it asked for a full customer record. It doesn’t know what system or systems it came from or how it was retrieved.


How does the XmlSerializer work? What ACL permissions does a process using it require?

XmlSerializer requires write permission to the system’s TEMP directory.

Why is catch(Exception) almost always a bad idea?


Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project.

What is the difference between Debug.Write and Trace.Write? When should each be used?

The Debug.Write call won’t be compiled when the DEBUG symbol is not defined (when doing a release build). Trace.Write calls will be compiled. Debug.Write is for information you want only in debug builds, Trace.Write is for when you want it in release build as well. And in any case, you should use something like log4net because that is both faster and better

What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

Debug build contain debug symbols and can be debugged while release build doesn’t contain debug symbols, doesn’t have [Contional(”DEBUG”)] methods calls compiled, can’t be debugged (easily, that is), less checking, etc. There should be a speed difference, because of disabling debug methods, reducing code size etc but that is not a guarantee (at least not a significant one)

Does JITting occur per-assembly or per-method? How does this affect the working set?

Contrast the use of an abstract base class against an interface?

In the interface all methods must be abstract, in the abstract class some methods can be concrete. In the interface no accessibility modifiers are allowed, which is ok in abstract classes

In the context of a comparison, what is object identity versus object equivalence?

How would one do a deep copy in .NET?

System.Array.CopyTo() - Deep copies an Array

Explain current thinking around IClonable.

IClonable interface is used to clone objects like constructor copy in c++

What is boxing?

Boxing is an implicit conversion of a value type to the type object
int i = 123; // A value type
Object box = i // Boxing
Unboxing is an explicit conversion from the type object to a value type
int i = 123; // A value type
object box = i; // Boxing
int j = (int)box; // Unboxing
Convertion of value type to ref type

Is string a value type or a reference type?

string is actually ref Type but some difference with other ref object
Value type - bool, byte, chat, decimal, double, enum , float, int, long, sbyte, short,strut, uint, ulong, ushort
Value types are stored in the Stack
Reference type - class, delegate, interface, object, string
Reference types are stored in the Heap