Thursday, July 16, 2009

Asp .net Web.config Configuration File

What is Web.Config File?


Web.config file, as it sounds like is a configuration file for the Asp .net web application

. An Asp .net application has one web.config file which keeps the configurations required for the corresponding application. Web.config file is written in XML with specific tags having specific meanings.

What is Machine.config File?


As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.


What can be stored in Web.config file?


There are number of important settings that can be stored in the configuration file. Here are some of the most frequently used configurations, stored conveniently inside Web.config file..


1. Database connections

2. Session States

3. Error Handling

4. Security


Database Connections:


The most important configuration data that can be stored inside the web.config file is the database connection string. Storing the connection string in the web.config file makes sense, since any modifications to the database configurations can be maintained at a single location. As otherwise we'll have to keep it either as a class level variable in all the associated source files or probably keep it in another class as a public static variable.


But it this is stored in the Web.config file, it can be read and used anywhere in the program. This will certainly save us a lot of alteration in different files where we used the old connection.


Lets see a small example of the connection string which is stored in the web.config file.


<configuration>


<appSettings>


<add key="ConnectionString"


value="server=localhost;uid=sa;pwd=;database=DBPerson" />


</appSettings>


</configuration>


As you can see it is really simple to store the connection string in the web.config file. The connection string is referenced by a key which in this case is "ConnectionString". The value attribute of the configuration file denotes the information about the database. Here we can see that if has database name, userid and password. You can define more options if you want.


There is a very good website that deals with all sorts of connection strings. Its called www.connectionstrings.com , in the website you will find the connection strings for most of the databases.


Lets see how we access the connection string from our Asp .net web application.


using System.Configuration;


string connectionString = (string )ConfigurationSettings.AppSettings["ConnectionString"];


The small code snippet above is all that is needed to access the value stored inside the Web.config file.

Session States:


Session in Asp .net web application is very important. As we know that HTTP is a stateless protocol and we needs session to keep the state alive. Asp .net stores the sessions in different ways. By default the session is stored in the asp .net process. You can always configure the application so that the session will be stored in one of the following ways.


1) Session State Service


There are two main advantages of using the State Service. First the state service is not running in the same process as the asp .net application. So even if the asp .net application crashes the sessions will not be destroyed. Any advantage is sharing the state information across a Web garden (Multiple processors for the same computer).


Lets see a small example of the Session State Service.


<sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:55455" sqlConnectionString="data source=127.0.0.1;user id=sa;password='' cookieless="false" timeout="20"/>


The attributes are self explanatory but I will go over them.


mode: This can be StateServer or SqlServer. Since we are using StateServer we set the mode to StateServer.


stateConnectionString: connectionString that is used to locate the State Service.


sqlConnectionString: The connection String of the sql server database.


cookieless: Cookieless equal to false means that we will be using cookies to store the session on the client side.


2) SQL Server


The final choice to save the session information is using the Sql Server 2000 database. To use Sql Server for storing session state you need to do the following:


1) Run the InstallSqlState.sql script on the Microsoft SQL Server where you intend to store the session.


You web.config settings will look something like this:

<sessionState mode = "SqlServer" stateConnectionString="tcpip=127.0.0.1:45565" sqlConnectionString="data source="SERVERNAME;user id=sa;password='' cookiesless="false" timeout="20"/>


SQL Server lets you share session state among the processors in a Web garden or the servers in a Web farm. Apart from that you also get additional space to store the session. And after that you can take various actions on the session stored.


The downside is SQL Server is slow as compared to storing session in the state in process. And also SQL Server cost too much for a small company.

3) InProc:


This is another Session State. This one is mostly used for development purposes. The biggest advantage of using this approach is the applications will run faster when compared to other Session state types. But the disadvantage is Sessions are not stored when there is any problem that occurs with the application, when there is a small change in the files etc., Also there could be frequent loss of session data experienced..

Error Handling:


Error handling is one of the most important part of any web application. Each error has to be caught and suitable action has to be taken to resolve that problem. Asp.net web.config file lets us configure, what to do when an error occurs in our application.


Check the following xml tag in the web.config file that deals with errors:


<customErrors mode = "On">


<error statusCode = "404" redirect = "errorPage.aspx" />


</customErrors>


This tells the Asp.net to display custom errors from a remote client or a local client and to display a page named errorPage.aspx. Error "404" is "Page not found" error.


If custom error mode is turned "off" than you will see Asp.net default error message. This error messages are good for debugging purposes but should never be exposed to the users. The users should always be presented with friendly errors if any.

Security:


The most critical aspect of any application is the security. Asp.net offers many different types of security method which can be used depending upon the condition and type of security you need.


1) No Authentication:


No Authentication means "No Authentication" :) , meaning that Asp.net will not implement any type of security.


2) Windows Authentication:


The Windows authentication allows us to use the windows user accounts. This provider uses IIS to perform the actual authentication, and then passes the authenticated identity to your code. If you like to see that what windows user is using the Asp.net application you can use:


User.Identity.Name;


This returns the DOMAIN\UserName of the current user of the local machine.


3) Passport Authentication:


Passport Authentication provider uses Microsoft's Passport service to authenticate users. You need to purchase this service in order to use it.


4) Forms Authentication:


Forms Authentication uses HTML forms to collect the user information and than it takes required actions on those HTML collected values.


In order to use Forms Authentication you must set the Anonymous Access checkbox checked. Now we need that whenever user tries to run the application he/she will be redirected to the login page.


<authentication mode="Forms">


<forms loginUrl = "frmLogin.aspx" name="3345C" timeout="1"/>


</authentication>


<authorization>


<deny users="?" />


</authorization>


As you can see we set the Authentication mode to "Forms". The forms loginUrl is the first page being displayed when the application is run by any user.


The authorization tags has the deny users element which contains "?", this means that full access will be given to the authenticated users and none access will be given to the unauthenticated users. You can replace "?" with "*" meaning that all access is given to all the users no matter what.

Final Words:


As you have seen that Web.config file plays a very important role in the over all Asp.net application. There are a lot more features that I have not discussed which includes caching. Try using web.config file when you need to configure the overall application.

Tuesday, July 14, 2009

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.

Thursday, July 2, 2009

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.

Thursday, May 21, 2009

Debate(part II) - .NET V. PHP: Top 6 Reasons to Use .NET

1. Speed

Just like all .NET applications, ASP.NET applications are compiled. This makes them much faster than PHP, whose applications are interpreted. To achieve the same effect with PHP, Zend and PHP accelerator must be installed on the server, and this is rarely the case at most Web hosting companies. Also, OO is much faster in ASP.NET than it is in PHP.

2. More Language Support

ASP.NET is written using "real" OO (Object Oriented) programming languages of your choice. PHP is just a simple scripting language in comparison to .NET languages like C++, VB.NET or C# -- languages that give you more control, and more reusability. That said, these languages are also harder to learn and master, and might be intimidating if you haven't been programming for very long. ASP.NET, for example, can't be picked up as easily as PHP, though C# is not very hard to learn if you already know PHP.

Another good thing about .NET is that it has multi-language support. You can currently write (or will be able to in the very near future) ASP.NET applications in C++, C#, Visual Basic.NET, Jscript.NET, Python, Perl, Java (J#), COBOL, Eiffel and Delphi. You may even find yourself writing your ASP.NET applications in PHP in the future -- it's not impossible!

What's nice about this is that you can mix the code. can instantiate an object in C# from a class written in C++ or VB.NET. This increases the programmer hiring pool for companies, and improves your chances of finding a suitable pre-written class for your project on the Web.

3. Your Choice of Development Environments

This is an area where ASP.NET shines!

Microsoft has released a free development environment for ASP.NET called Web Matrix, which blows all other free development environments for PHP out of the water. It has a built-in Web server, database administration interface FTP integration, and more. Not only that, Microsoft has also released MSDE -- a free development edition of MS SQL server. It has precisely all the features of the full MS SQL server 2000, and any application you write for MSDE will run fine on MS SQL Server.

If you can afford Visual Studio .NET, it, too, offers some amazing qualities. It allows you to:

* automatically create reports and diagrams from your databases,
* debug the code line by line, while at the same time seeing what happens in the application,
* assign a temporary value to a variable in the middle of execution, in order to test out different scenario,
* hover the cursor over variables in your code while debugging, to see what value they have "right now",

...and much more.

4. It's Part of .NET

ASP.NET is a part of .NET, and that benefit is too large to simply ignore. If you know how to write ASP.NET applications, you know how to write ordinary applications too. Even windows apps, if you read up a little on the Windows Forms classes (as opposed to the Web Forms). PHP has PHP-GTK, but it's currently very immature compared to .NET.

5. It's Cheaper to Develop for

Didn't expect that one, did ya? It even surprised me! Due to the fact that ASP.NET is such a powerful application, and it's offered for free (including the code editor, Web server, and FTP client), I actually ended up paying less ($0) than I did for my PHP Development Environment composed of UltraEdit ($35), Bullet Proof FTP ($30) and mySQLfront ($0). With that said, hosting ASP.NET is still more expensive than PHP.

6. It's Cross-Platform

.NET is currently pretty much tied to the Windows platform. This is a bad thing, but I'm quite confident that .NET will become very cross-platform in a few years. Why? A while back, Microsoft released Rotor, a Shared Source implementation of the CLR (CLR = The thing that runs code) and most of the non-windows specific class libraries for Windows and BSD Unix, with source code for both. When I first heard this, I didn't believe it -- that REALLY didn't sound like something Microsoft would do. And when I realized that it was in fact true, I expected Rotor to be the smallest and most feeble implementation Microsoft could possibly get away with.

I couldn't have been more wrong. Rotor hasn't been built on the cheap -- it's practically identical to its commercial counterpart in most important respects. .NET also has a very powerful Platform Abstraction Layer, making ports to other operating systems pretty easy to achieve. Not only that, but the CLI and C# are now standardized by ECMA. And the Mono project, with Ximian behind it, is working on an Open Source implementation of the .NET framework right now. All these factors lead me to believe that the chances for .NET to become cross-platform are very high.
Try it!

But don't take my (or Harry's) word as gospel! Try ASP.NET out for yourself. First, download the .NET framework (21MB), then download MSDE (MS SQL 2000-light I talked about earlier -- 33MB) and finally, ASP.NET Web Matrix (1.2MB).

Once you have these installed, you're ready to develop ASP.NET applications -- go check out the official ASP.NET Quickstart Tutorials, or even better, Kevin Yank's excellent article series on beginning ASP.NET. Enjoy!

Hear both side ot the argument! Find out why the opposition thinks PHP is superior, and make up your own mind!

Debate(part I) - .NET V. PHP: Top 6 Reasons to Use .NET

What is the .NET Framework?

The .NET Framework consists of two main parts:

1. the CLR (the thing that runs code), and

2. a hierarchical set of class libraries (Think PHP functions + the PEAR libraries, extend them a little, and have them organized in a very nice hierarchical structure). Included in those class libraries are ASP.NET, ADO.NET (a data access system) and Windows Forms (classes for building windows apps).


The CLR can run code written in any language that's adapted to .NET, and can run it on any operating system that has a version of the CLR. In other words, kind of like Java that doesn't have to be written in Java.
An Example: The Web Forms Framework
ASP.NET has a kind of templating system on steroids called Web Forms. I mention this first because it's this system that got me interested in ASP.NET in the first place, and is, in my opinion, the best feature of ASP.NET. There's nothing like it in PHP yet, to my knowledge. It goes something like this:
<select id="ColorSelect" runat="server">

<option>SkyBlue</option>

<option>LightGreen</option>

<option>Gainsboro</option>

<option>LemonChiffon</option>

</select>

<span id="Span1" runat="server">Some text.</span>

Notice that the above is just ordinary HTML, with the addition of the runat="server" attribute in the <span> and <select> tags. Now, to add an option to this selectbox, you would include the following in your ASP.NET code (which, by the way, can be separated completely from the HTML):
ColorSelect.Items.Add('AzureBlue');
And to manipulate the <span> tag, you would do this:
Span1.Style["background-color"] = "red";

Span1.InnerHTML = "Changed text!";
...and the system outputs 100% valid XHTML to the browser:
<select id="ColorSelect">

<option>SkyBlue</option>

<option>LightGreen</option>

<option>Gainsboro</option>

<option>LemonChiffon</option>

<option>AzureBlue</option>

</select>

<span style="background-color: red;">Changed text!</span>
Besides the fact that this is very cool, it also makes collaboration with the clueless HTML/Designer guys much easier. This is only a very simple example of what the Web forms framework is capable of, and if you're interested, you can check out more examples in the ASP.NET Quickstart tutorials over at GotDotNet.



Continued in next article....

Monday, March 30, 2009

What is the difference between repeater over datalist and datagrid?

The Repeater class is not derived from the WebControl class, like the DataGrid and DataList. Therefore, the Repeater lacks the stylistic properties common to both the DataGrid and DataList. What this boils down to is that if you want to format the data displayed in the Repeater, you must do so in the HTML markup.
The Repeater control provides the maximum amount of flexibility over the HTML produced. Whereas the DataGrid wraps the DataSource contents in an HTML < table >, and the DataList wraps the contents in either an HTML < table > or < span > tags (depending on the DataList's RepeatLayout property), the Repeater adds absolutely no HTML content other than what you explicitly specify in the templates.
While using Repeater control, If we wanted to display the employee names in a bold font we'd have to alter the "ItemTemplate" to include an HTML bold tag, Whereas with the DataGrid or DataList, we could have made the text appear in a bold font by setting the control's ItemStyle-Font-Bold property to True.
The Repeater's lack of stylistic properties can drastically add to the development time metric. For example, imagine that you decide to use the Repeater to display data that needs to be bold, centered, and displayed in a particular font-face with a particular background color. While all this can be specified using a few HTML tags, these tags will quickly clutter the Repeater's templates. Such clutter makes it much harder to change the look at a later date. Along with its increased development time, the Repeater also lacks any built-in functionality to assist in supporting paging, editing, or editing of data. Due to this lack of feature-support, the Repeater scores poorly on the usability scale.
However, The Repeater's performance is slightly better than that of the DataList's, and is more noticeably better than that of the DataGrid's. Following figure shows the number of requests per second the Repeater could handle versus the DataGrid and DataList

Explain < @OutputCache% > and the usage of VaryByParam, VaryByHeader.

OutputCache is used to control the caching policies of an ASP.NET page or user control. To cache a page @OutputCache directive should be defined as follows < %@ OutputCache Duration="100" VaryByParam="none" % >
VaryByParam: A semicolon-separated list of strings used to vary the output cache. By default, these strings correspond to a query string value sent with GET method attributes, or a parameter sent using the POST method. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each specified parameter. Possible values include none, *, and any valid query string or POST parameter name.
VaryByHeader: A semicolon-separated list of HTTP headers used to vary the output cache. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each specified header

What is the difference between HTTP-Post and HTTP-Get?

As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these methods encode request parameters as name/value pairs in the HTTP request.
The GET method creates a query string and appends it to the script's URL on the server that handles the request.
The POST method creates a name/value pairs that are passed in the body of the HTTP request message.
Name and describe some HTTP Status Codes and what they express to the requesting client.
When users try to access content on a server that is running Internet Information Services (IIS) through HTTP or File Transfer Protocol (FTP), IIS returns a numeric code that indicates the status of the request. This status code is recorded in the IIS log, and it may also be displayed in the Web browser or FTP client. The status code can indicate whether a particular request is successful or unsuccessful and can also reveal the exact reason why a request is unsuccessful. There are 5 groups ranging from 1xx - 5xx of http status codes exists.
101 - Switching protocols.
200 - OK. The client request has succeeded
302 - Object moved.
400 - Bad request.
500.13 - Web server is too busy.

What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?

ASP.NET provides three distinct ways to store session data for your application: in-process session state, out-of-process session state as a Windows service, and out-of-process session state in a SQL Server database. Each has it advantages.
1.In-process session-state mode
Limitations:
* When using the in-process session-state mode, session-state data is lost if aspnet_wp.exe or the application domain restarts.
* If you enable Web garden mode in the < processModel > element of the application's Web.config file, do not use in-process session-state mode. Otherwise, random data loss can occur.
Advantage:
* in-process session state is by far the fastest solution. If you are storing only small amounts of volatile data in session state, it is recommended that you use the in-process provider.
2. The State Server simply stores session state in memory when in out-of-proc mode. In this mode the worker process talks directly to the State Server
3. SQL mode, session states are stored in a SQL Server database and the worker process talks directly to SQL. The ASP.NET worker processes are then able to take advantage of this simple storage service by serializing and saving (using .NET serialization services) all objects within a client's Session collection at the end of each Web request
Both these out-of-process solutions are useful primarily if you scale your application across multiple processors or multiple computers, or where data cannot be lost if a server or process is restarted.

When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET applic

The tool can be launched with a set of optional parameters. Option "i" Installs the version of ASP.NET associated with Aspnet_regiis.exe and updates the script maps at the IIS metabase root and below. Note that only applications that are currently mapped to an earlier version of ASP.NET are affected

When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

On Windows 2003 (IIS 6.0) running in native mode, the component is running within the w3wp.exe process associated with the application pool which has been configured for the web application containing the component.
On Windows 2003 in IIS 5.0 emulation mode, 2000, or XP, it's running within the IIS helper process whose name I do not remember, it being quite a while since I last used IIS 5.0.

Wednesday, March 25, 2009

What are the advantages and disadvantages of viewstate?

The primary advantages of the ViewState feature in ASP.NET are:
1. Simplicity. There is no need to write possibly complex code to store form data between page submissions.
2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to persist the values of some fields but not others.
There are, however a few disadvantages that are worth pointing out:
1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the session
approach, values can be stored in the session and accessed from other pages. This is not possible with ViewState, so storing
data into the session must be done explicitly.
2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to the back
end using some form of data object.

Monday, March 23, 2009

What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?

ASP.NET provides three distinct ways to store session data for your application: in-process session state, out-of-process session state as a Windows service, and out-of-process session state in a SQL Server database. Each has it advantages.
1.In-process session-state mode
Limitations:
* When using the in-process session-state mode, session-state data is lost if aspnet_wp.exe or the application domain restarts.
* If you enable Web garden mode in the < processModel > element of the application's Web.config file, do not use in-process session-state mode. Otherwise, random data loss can occur.
Advantage:
* in-process session state is by far the fastest solution. If you are storing only small amounts of volatile data in session state, it is recommended that you use the in-process provider.
2. The State Server simply stores session state in memory when in out-of-proc mode. In this mode the worker process talks directly to the State Server
3. SQL mode, session states are stored in a SQL Server database and the worker process talks directly to SQL. The ASP.NET worker processes are then able to take advantage of this simple storage service by serializing and saving (using .NET serialization services) all objects within a client's Session collection at the end of each Web request
Both these out-of-process solutions are useful primarily if you scale your application across multiple processors

Sunday, March 22, 2009

What does aspnet_regiis -i do ?

Aspnet_regiis.exe is The ASP.NET IIS Registration tool allows an administrator or installation program to easily update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool. The tool can also be used to display the status of all installed versions of ASP. NET, register the ASP.NET version coupled with the tool, create client-script directories, and perform other configuration operations.

When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime is used for the application.

The tool can be launched with a set of optional parameters. Option "i" Installs the version of ASP.NET associated with Aspnet_regiis.exe and updates the script maps at the IIS metabase root and below. Note that only applications that are currently mapped to an earlier version of ASP.NET are affected

What is validationsummary server control?where it is used?.

The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property. The error message displayed in the ValidationSummary control for each validation control on the page is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed in the ValidationSummary control for that validation control. You can also specify a custom title in the heading section of the ValidationSummary control by setting the HeaderText property.
You can control whether the ValidationSummary control is displayed or hidden by setting the ShowSummary property. The summary can also be displayed in a message box by setting the ShowMessageBox property to true.

Wednesday, March 18, 2009

Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component?

• Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option.
• Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors.
• Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically.
• Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet.
• When not to use Web Services: Single machine Applicatons When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Componets as there is very little overhead.
• Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps

What are ASP.NET Web Forms? How is this technology different than what is available though ASP?

Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

Monday, March 16, 2009

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

Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive.
Response.Redirect() :client know the physical location (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

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

Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip, then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false.

Should validation (did the user enter a real date) occur server-side or client-side? Why?

It should occur both at client-side and Server side.By using expression validator control with the specified expression ie.. the regular expression provides the facility of only validatating the date specified is in the correct format or not. But for checking the date where it is the real data or not should be done at the server side, by getting the system date ranges and checking the date whether it is in between that range or not.

What is different b/w webconfig.xml & Machineconfig.xml

Web.config & machine.config both are configuration files.Web.config contains settings specific to an application where as machine.config contains settings to a computer. The Configuration system first searches settings in machine.config file & then looks in application configuration files.Web.config, can appear in multiple directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. There is only Machine.config file on a web server.
If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users?
Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config.
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1; user id=sa; password="
cookieless="false"
timeout="30"
/>
You can specify mode as “stateserver” or “sqlserver”.
Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one
"One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.

What event handlers can I include in Global.asax?

Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,
Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_End
You can optionally include "On" in any of method names. For example, you can name a BeginRequest event handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web Services (they're designed for ASP.NET applications in general, whereas .NET XML Web Services are specialized instances of an ASP.NET app). For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication.

Thursday, March 12, 2009

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

AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties.

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

In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems.
As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

What are ASP.NET Web Forms? How is this technology different than what is available though ASP?

Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application.

Is it possible to prevent a browser from caching an ASPX page?

Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here:

<%@ Page Language="C#" %>


<%
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
%>


SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.

How does dynamic discovery work?

ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.
Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by uncommenting the line in the section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security

What are VSDISCO files?

VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host directory and any subdirectories not noted in elements:

xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">





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

Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn't have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC++. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer.

What does AspCompat="true" mean and when should I use it?

AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:
<%@ Page AspCompat="true" %>
Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually, the thread that processes the request for the page) and the COM objects it creates share an apartment. AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment boundaries.
Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both.

Wednesday, March 4, 2009

What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?

RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs. <%@ Reference Control="MyControl.ascx" %>

Can a user browsing my Web site read my Web.config or Global.asax files?

No. The section of Machine.config, which holds the master configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. You can modify it by editing Machine.config or including an section in a local Web.config file.

Monday, March 2, 2009

How do I send e-mail from an ASP.NET application?

MailMessage message = new MailMessage ();
message.From = ;
message.To = ;
message.Subject = "Scheduled Power Outage";
message.Body = "Our servers will be down tonight.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (message);
MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's System.Web.Mail namespace. Due to a security change made to ASP.NET just before it shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though "localhost" is the default. In addition, you must use the IIS configuration applet to enable localhost (127.0.0.1) to relay messages through the local SMTP service.

Is it necessary to lock application state before accessing it?

Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:
Application.Lock ();
Application["ItemsSold"] = (int) Application["ItemsSold"] + 1;
Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1;
Application.UnLock ();
By locking application state before updating it and unlocking it afterwards, you ensure that another request being processed on another thread doesn't read application state at exactly the wrong time and see an inconsistent view of it. If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state?
Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASP.NET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event.

How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?

Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list, check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.
Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a
<%@ Page Debug="true" %> statement at the top of an ASPX file or a statement in a Web.config file.

Sunday, March 1, 2009

What are the different types of caching?

Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput CachingFragment CachingData
Output Caching: Caches the dynamic output generated by a request. Some times it is useful to cache the output of a website even for a minute, which will result in a better performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %>
Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%>
Data Caching: Caches the objects programmatically. For data caching asp.net provides a cache object for eg: cache["States"] = dsStates;

What are user controls and custom controls?

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.

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.

How to Manage state in ASP.NET?

We can manage the state in two ways
Client based techniques are Viewstate, Query strings and Cookies.
Server based techniques are Application and Session

Friday, February 27, 2009

What are different types of directives in .NET?

directives allow you to specify page properties and configuration information for the page. The directives are used by ASP.NET as instructions for how to process the page, but they are not rendered as part of the markup that is sent to the browser...
@Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %>
@Control:Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %>
@Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @ Import Namespace="System.web" %>
@Implements: Indicates that the current page or user control implements the specified .NET framework interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %>
@Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %>
@Assembly: Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %>
@OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page<%@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring" VaryByHeader="headers" VaryByParam="parametername" %>
@Reference: Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared.

Thursday, February 26, 2009

Asp.net - Dataset vs Datareader

To better improve the performance of a solution, we have to
understand the DataSet and DataReader and they have to be used correctly in the places they needed. Let see how they work...

DataReader
Datareader is like a forward only recordset. It fetches one
row at a time so very less Network Cost compare to DataSet(Fetches all the rows at a time). DataReader is readonly so we cannot do any transaction on them. DataReader will be the best choice where we need to show the data to the user which requires no transaction ie reports. Due to DataReader is forward only we cannot fetch the data randomly. .NET Dataproviders optimizes the datareaders to handle the huge amount of data.

DataSet
DataSet is always a bulky object that requires lot of memory space compare to DataReader. We can say the dataset as a small database coz it stores the schema and data in the application memory area. DataSet fetches all data from the datasource at a time to its memory area. So we can traverse through the object to get required data like qureying database.

The dataset maintains the relationships among the datatables inside
it. We can manipulate the realational data as XML using dataset.We can do transactions (insert/update/delete) on them and finally the modifications can be updated to the actual database. This provides impressive flexibility to the application but with the cost of memory space. DataSet maintains the original data and the modified data seperately which requires more memory space. If the amount of data in the dataset is huge
then it will reduce the applications performance dramatically.

The following points will improve the performane of a dataset...

1. Don't use the commandbuilder to generate the sql statements.
Though it reduces the development time the query generated

by the command builder will not be always as required. For example
To update the details of an author table the command

builder will generate a query like this ...

Query generated by CommandBuilder

UPDATE authors
SET
au_id = ?, au_fname = ?, au_lname = ?, phone = ?,
zip = ?, state = ?, city = ?, address = ?
WHERE
(au_id = ?)
AND (address = ? OR ? IS NULL AND address IS NULL)
AND (au_fname = ?)
AND (au_lname = ?)
AND (city = ? OR ? IS NULL AND city IS NULL)
AND (phone = ?)
AND (state = ? OR ? IS NULL AND state IS NULL)
AND (zip = ? OR ? IS NULL AND zip IS NULL)

But we can write much more efficient query than the above like
this ..
UPDATE authors
SET
au_id = ?, au_fname = ?, au_lname = ?, phone = ?,
zip = ?, state = ?, city = ?, address = ?
WHERE
(au_id = ?)

2. Always select the columns required in the quries. Don't use "select * from ". Take an example of authors table which has the author id , name, address, image. For showning the author name,address if we use select * then the image column also fetched from the database which requires more memory and NetWork Cost will be more due the amount of data. This will reduce the applications performance.

3. Always try to use the parameter collection for the stored
procedures. We can execute the stored proceduers in two ways.
a. we can create a string as a query and can execute it.
Ex "getAuthor(7689)".
b. we can create a command object. Assign the Stored Procedure
name to the commandtext property. Specify the commandtype as stored procedure. Create a parameter for the value passed to the SP and execute.
Ex:
SqlCommand sqlcmd = new SqlCommand();
sqlcmd.CommandText="getAuthors";
sqlcmd.CommandType= CommandType.StoredProcedure;
SqlParameter sqlparam = new SqlParameter
("@au_id",SqlDbType.Int);
sqlparam.Value = 7689;
sqlcmd.Parameters.Add(sqlparam);
sqlcmd.Connection= con;
sqlcmd.ExecuteReader();

There are lot of difference between the way the two quries executed.
The first query will be sent to the database server as a string though we think we are passing the author id as int. The database server will parse the query and will determine the datatype of the parameter. This extra processing will increase the execution time.
But while executing the second query the native datatype of the
parameter is sent to the database server as network packets throuh RPC.

Wednesday, February 18, 2009

Asp.Net Beginners

ASP.NET
ASP.NET is a platform that excels in the realm of Web application development. It also can be used in stand-alone applications. ASP.NET produces HTML content—some static and unchanging, some dynamic and changeable.

The static HTML content that's output using ASP.NET is similar to what you can create with Notepad or FrontPage. When you use an authoring tool such as FrontPage, you typically use the WYSIWYG editor and save the file somewhere—usually to a Web server. The HTML content is then served up when a client machine makes a request to the Web server.

Many times, though, the content needs to adapt itself to the situation. A particular user might need additional menu choices in the Web application. Or if your business offers specials each Tuesday, you might need special images to appear next to those items in you product catalog each Tuesday. As a technology for dynamically creating HTML, ASP.NET works in instances such as these.

Many of you have developed ASP applications in which the files all have .asp extensions. ASP.NET application files have an .aspx extension to differentiate them from ASP files. Because their extensions are different, both classic ASP and ASP.NET can function side-by-side in the same Web site.

ASP.NET files have a major performance advantage over ASP files. The first time they are requested, they are compiled into native code, which makes them execute much faster than the interpreted ASP files.

In classic ASP, you didn't have many language choices. Anything you could do in HTML, such as JScript and JavaScript, were available. For server-side programming, VBScript was one choice, and for ISAPI programming, VB and C++. Now, with ASP.NET, you get VB, C#, and JScript out of the box. And other languages—Cobol, RPG, Pascal, and many others—are under development by third-party vendors. ASP.NET was developed from the ground up to be language agnostic—in other words, any language should give you similar final results.

In terms of extra effort required, this multiple-language support and runtime compilation to native code doesn't come at any price to developers. To save an ASP.NET file, all you have to do is save it to disk—no compile button and no other steps.

ASP.NET has a new control-based, event-driven execution model. You can hook a Page_Load() method, an event that a server-side control fires off such as an OnItemCommand() method, or any other event that is available. The naming of Page_Load() in C# is the default behavior. The event handler could be named iRool and not affect whether the event was called. By comparison, in VB.NET, similar methods end with handles Page.Load.

In all, the new model that ASP.NET follows offers these benefits: It requires that you write less code, it encapsulates functionality into easy-to-use classes, and it reduces the amount of spaghetti code you'll be inclined to write.

Many of the applications we'll write in this book use Visual Studio .Net as the development tool, with ASP.NET as the deployment and runtime environment. We chose this combination because of the heavy emphasis that Microsoft is placing on distributed applications, and the rising need for you to develop enterprise and distributed applications.

About Me

Hyderabad, Andhra Pradesh, India
I'm a MCA graduate working as a Web Developer.