LogoASPAlliance: Articles, reviews, and samples for .NET Developers
Hosting a .NET Application in a Web Farm
by Tejaswini Das
Average Rating: 
Views (Total / Last 10 Days): 40905/ 94


A Web server farm or simply Web farm is a group of computers acting as servers and housed together in a single location. A server farm is sometimes called a server cluster. A Web server farm can be either (1) a Web site that has more than one server or (2) an Internet service provider that provides Web hosting services using multiple servers.

What is the use of web farm?

To Increasing Scalability through IIS Load Balancing:-

Web farms not only increase performance by reducing the load on each server in the Web farm, they also increase availability. If one server in the Web farm is disabled (such as being taken offline for maintenance), other servers in the Web farm take over, so users are never aware of the offline server.

Steps to Remember while hosting site
1. Enable View State

In a Web farm, each client request can go to a different machine on every postback. Because of this behavior, you cannot leave the validationKey attribute set to AutoGenerate in the Machine.config file. Instead, you must set the value of the validationKey attribute to a fixed string that is shared by all the machines on the Web farm.

Generate Machine Key Elements for Web Farm

The <machineKey> Element configures keys to use for encryption and decryption of forms authentication cookie data and viewstate data, and for verification of out-of-process session state identification.

Here is an example of Configuration Structure for the element:

Listing 1

    <machineKey validationKey="AutoGenerate|value[,IsolateApps]" 

The validationKey attribute specifies the key used for validation of encrypted data. The validationKey is used when enableViewStateMAC is true to create a message authentication code (MAC) to ensure that the view state has not been tampered with. ValidationKey is also used to generate out-of-process, application-specific session ID's to ensure that the session state variables are isolated between sessions.

The keys created will be used for the validationKey and the decryptionKey attributes of the <machineKey> section in the <system.web> element in the Machine.config and the Web.config files.

Create the project

1. Start Microsoft Visual Studio .NET.

2. On the File menu, point to New and then click Project.

3. In the Project Types area, click Visual Basic Projects.

4. In the Templates area, click Console Application.

5. In the Name text box, type GenerateKey and then click OK.   

Write the code to generate the keys

In this program we will pass two parameters as command line arguments. The first argument is the number of bytes that will be used to generate decryption key and the second argument is the number of bytes used to generate the validation key.

The code uses a random number generator to create a random number of bytes based on the command-line arguments. After the random bytes are created, the bytes are formatted into a hexadecimal string that is suitable for use in the .config files.

1.      Add a new class file named KeyCreator to your Visual Basic project.

2.      Replace the existing code in the KeyCreator.vb file with the following code:

Listing 2

Imports System
Imports System.Text
Imports System.Security.Cryptography
Namespace Crypto
    Public Class KeyCreator
        Public Sub CreateMachineKey()
            Dim commandLineArgs As String()
            commandLineArgs = System.Environment.GetCommandLineArgs()
            Dim decryptionKey As String
            decryptionKey = CreateKey(System.Convert.ToInt32(commandLineArgs(1)))
            Dim validationKey As String
            validationKey = CreateKey(System.Convert.ToInt32(commandLineArgs(2)))
            Console.WriteLine( _
"<machineKey validationKey=""{0}"" decryptionKey=""{1}"" validation=""SHA1""/>", _
            validationKey, decryptionKey)
        End Sub
        Public Function CreateKey(ByVal numBytes As IntegerAs String
            Dim rng As RNGCryptoServiceProvider = New RNGCryptoServiceProvider()
            Dim buff(numBytes - 1) As Byte
            Return BytesToHexString(buff)
        End Function
        Public Function BytesToHexString(ByVal bytes As Byte()) As String
            Dim hexString As StringBuilder = New StringBuilder(64)
            Dim counter As Integer
            For counter = 0 To bytes.Length - 1
                hexString.Append(String.Format("{0:X2}", bytes(counter)))
            Return hexString.ToString()
        End Function
    End Class
End Namespace

3.      Open the Module1.vb file that is created by default and then add the following code in the Main sub routine.

Listing 3

Dim MyKeyCreator As New Crypto.KeyCreator()

4.      Save the application.

5.      Build the application.

Generate the hashes

Run the application from a command prompt and then pass in two integer values that are the size of the decryption and the validation keys. If you named the console application HashConfigVb.exe, type the following syntax at the command prompt in the Bin directory of the application: GenerateKey.exe 24 64.

The application should return output that is similar to the following:

Listing 4

<machineKey validationKey="08CE6B478DCE73..........E566D8AC5D1C045BA60"

Note: Because the code uses a random number generator, the output is different each time.

Update the configuration file

1. Locate the Machine.config file.

2. Locate the <system.web> section in the configuration file.

3. Replace the <machineKey> section with the output from the console application. If the <machineKey> section does not exist, create it.

4. Save the configuration file.

5. Restart IIS on all servers in the Web farm for the Machine.config changes to take effect.

2. Session Maintenance

The default ASP.NET in-process session state handling, results in server affinity and cannot be used in a Web farm scenario. For Web farm deployments, the session state must be stored out of process in either the ASP.NET State service or a SQL Server database.

Out of Process Mode

In the Out of Process mode, the session information is stored in a separate “state server” process. The worker process ("aspnet_wp.exe") will communicate with the state server ("aspnet_state.exe") to retrieve session information. However, the use of state server mode can affect the performance of the application by 10-15%. The main reason for this performance hamper is due to the fact that session information resides in a separate process (i.e. in a memory area outside the direct control of the asp_net worker process). So with every request, the worker process has to get the session values from a separate process.

To keep session information outside the worker process, the objects inside the session must be serializable. So with end of every request, the objects inside the session are serialized and with the beginning of each request, the objects are de-serialized.

To continue to use the state server model, the sessionstate parameter in the web.config file needs to be updated.

Listing 5:

    sqlconnectionstring="data source=;user id=userid;password=password"

The default data source is set to the local machine so if the state server is on a different machine as that of the application then the correct machine name should be given on the web.config file.

SQL Server Mode

In the SQL Server mode the information is stored in the SQL Server rather than memory. But to use the SQL Server session state, we need to create the necessary tables and the stored procedures that ASP.NET will look for on the identified SQL Server. The SQL Server mode affects the performance to a greater degree, but makes the session information more secure as we can have two or more identical computers running SQL server for a single database. So if one computer fails another computer can take over and serve requests without session data loss.

For applications in ASP.NET 1.1 and SQL 2000

To configure to use the SQL Server mode, the sessionstate parameter in the web.config needs to be updated.

Listing 6

  sqlconnectionstring="data source=MySqlServer;user id=ASPState;password=1Gr8State"
  port="42424" />

Configure the SQL Server to store Session objects by running a script to create the ASPState database. Version 1.0 of the .NET Framework provides a state database configuration script in %SYSTEMROOT%\Microsoft.NET\Framework\v1.0.3705\InstallSqlState.sql. If you open the file, you will see a statement to create a database called ASPState.

For applications in ASP.NET 2.0 and SQL 2005

To install the session state database on SQL Server, run Aspnet_regsql.exe tool and supply the following information with the command.

• The name of the SQL Server instance, using the -S option

• The logon credentials for an account that has permission to create a database on a computer running SQL Server: Use the -E option to use the currently logged-on user, or use the -U option to specify a user ID along with the -P option to specify a password.

• The -ssadd command-line option to add the session state database

Listing 7

aspnet_regsql.exe -S <SQL Server name> -U <User Name> -P <Password> -ssadd -sstype p

You can run Aspnet_regsql.exe without any command-line arguments to run a wizard that will walk you through specifying connection information for your SQL Server database and installing or removing the database elements for supported features. You can also run Aspnet_regsql.exe as a command-line tool to specify database elements for individual features to add or remove.

To run the wizard, run Aspnet_regsql.exe without any command-line arguments, as shown in the following example.

Listing 8


This article examined the concept of hosting a Microsoft .NET application in a Web Farm with the help of examples.

Tejaswini Das

Mindfire solutions

Product Spotlight
Product Spotlight 

©Copyright 1998-2021  |  Page Processed at 2021-10-21 1:50:15 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search