Boost Performance by Using a CDN in Your ASP.NET Site

A CDN (Content Delivery Network) is simply a network of data centers spread across the globe which serve static content to a user from the nearest available data center. Thus a request for a static file by a user in Australia
would be served from a nearby AsiaPac data center instead of the US (where the main site may to served from). This reduces the latency and therefore boosts performance.

A secondary factor boosting performance is that typically browsers can only open up 2 simultaneous connects to a host, therefore if your web page will require 20 file requests and all static files are on the same server the requests are
queued two at a time. If a CDN is used, the browser can open up more simultaneous file requests and so boost performance.

Which CDN ?

There are numerous CDNs to choose from, personally I use the Rackspace CloudFiles. Rackspace recently partnered with Akamai and so the CDN network is top notch – although the tools are quite weak. It is not possible to FTP a file
to a CDN but the FireUploader utility for Firefox is satisfactory (note that this had some issues with Firefox 4.0 when I tested it and as such I am still using it with Firefox 3.6).

I won’t list all available CDN options as I have not tried that many, but I also had a good experience with MaxCDN, although their pricing structure is quite unusual and so you should carefully examine this to guage your costs.

One thing to note, Amazon’s S3 storage solution is NOT a CDN. All files served from S3 are served from a single location and not from an array of data centers.  Amazon does have a CDN offering – CloudFront, however I would not recommend this as it did not perform well in any of my testing. The Azure CDN offering had a similar performance to the CloudFront product in my experience and so I wouldn’t recommend it.

How to Use a CDN

Using a CDN is very simple, just upload your static files to the CDN and then set the src attribute of the element (such as an <img> tag).

When a file is requested for the first time it will first be served from the central data center and then cached at the edge location (ie worldwide data center nearest to the requesting user). All subsequent requests will be served from the cache of the edge location until the TTL (Time To Live) value has expired. This can be a gotcha if you are updating the files. This typically happens a lot with css files. Therefore if you update your site’s css file, then upload it to your CDN, site users around the worldwide may be served a cached version of the old file. To get around this you can specify version numbers for your css files, in this way each file is unique and when you push an update the CDN will request the new css file from the central store before caching it.
By way of example if you look at the source for this SharePoint article you will see that most of the static files are served from a CDN.

Including ASP.NET Membership in an Existing Database

By default, when adding ASP.NET Membership to your web app a new ASP.NET Membership database will be created. However, in many circumstances you may wish the Membership database to be part of your  main application database. To do this simply navigate to \Windows\Microsoft.NET\Framework\v2.0.50727 (use this path even if you are using ASP.NET 4.0 in your application as the Membership database has not changed since ASP.NET 2).

Then find and run the aspnet_regsql.exe program. This will bring up a dialog allowing you to specify the target database to incorporate the ASP.NET Membership tables and stored procedures :

ASP.NET Membership database inclusion dialog

The final step is to ensure that the all connection string references to the membership provider in the web.config point to this database. Don’t forget if you are using Roles that the role provider specified in the web.config must also point to this database (otherwise ASP.NET will automatically create a new database for the roles when the app is run).

Sending Mail from a .NET App Using Amazon SES (Simple Email Service)

Amazon’s Simple Email Service (SES) is a great solution for any project which requires bulk emails. the primary advantage of SES is cost, at $0.10 per 1000 emails sent it is between 5-10x cheaper than other alternatives such as SendGrid. There is a downside to the SES service, however and it is that it currently doesn’t provide an SMTP wrapper so whilst SendGrid and others allow you to simple change your SMTP settings, with SES you will have to do a bit more work.

Amazon (AWS) provides a very useful .NET SDK (complete with dll’s for .NET 2.0, 3.5 and 4.0) which you can simply copy into your project and start calling the Amazon functions from a .NET app such as an ASP.NET site. You can download the SDK here.

The below code shows a simple example of how to use the Amazon AWS SDK in .NET to send emails.

Dim listColl As New System.Collections.Generic.List(Of String)
'//TODO - Write a simple loop to add the recipents email addresses to the listColl object.

Dim client As New Amazon.SimpleEmail.AmazonSimpleEmailServiceClient("aws_public_key_here", "aws_private_key_here")

Dim mailObj As New SendEmailRequest
Dim destinationObj As New Destination(listColl)
mailObj.Source = "from@youremail.com"  '//The from email address
mailObj.ReturnPath = "bounce@youremail.com" '//The email address for bounces
mailObj.Destination = destinationObj

'//Create Message
Dim emailSubjectObj As New Amazon.SimpleEmail.Model.Content("This is the Subject")
Dim emailBodyContentObj As New Amazon.SimpleEmail.Model.Content("This is the Body<br /><em>In Html</em>")

Dim emailBodyObj As New Amazon.SimpleEmail.Model.Body()
emailBodyObj.Html = emailBodyContentObj
Dim emailMessageObj As New Message(emailSubjectObj, emailBodyObj)
mailObj.Message = emailMessageObj

Dim response = client.SendEmail(mailObj)

That’s it, there’s really not a lot of heavy lifting to get starting using SES with .NET. the only thing I didn’t show in the code above is the loop for adding email addresses as strings to the generic collection, this loop will vary a lot depending on your exact requirements.
One thing to note above is that you will need to import the namespace Amazon.SimpleEmail.Model

AWS SES is not as full featured as a lot of solutions such as SendGrid, however it does have several useful features out-of-the-box such as the ability to perform email validation:

Dim testEmail As String = "anemail@domain.com"

Dim verRequest As New VerifyEmailAddressRequest()
verRequest.EmailAddress = testEmail
client.VerifyEmailAddress(verRequest)

This should get you going with SES, I will update this page once the service develops.

Using Sequence in SQL Server 2011 (an Alternative to Identity)

Using the Identity attribute for a column in SQL Server is a very convenient way to auto-increment a field in a row and generate unique ID’s for use as a primary key. SQL Server 2011 introduces Sequence, which is similar in many respects but is offers greater performance and flexibility – read our full tutorial on Using Sequence in SQL Server 2011.

ASP.NET Session State Best Practices

Session state is an integral part of many ASP.NET apps but it can also be a drag on performance or result in application errors if used inappropriately. Here are our ASP.NET Session State best practices to ensure you won’t be tripped up by any gotchas:

  • Do not overuse Session State for user data storage.
    One of the problems with Session State is that it is so convenient for user data storage – just store anything using Session["someName"] = someName.Text . This leads developers to overuse Session State and store data that would be better handled by another technique (for example, you can use ASP.NET Membership Profiles to store and retrieve user settings, or use caching for storing miscellaneous items).
  • Try to avoid storing complex objects in Session State.
    Session Sate can store objects of any type (including objects you create) however, they are stored by serializing and then de-serializing them which results in a big performance penalty. If possible try to only store ‘basic’ types such as Integer, Decimial, String, DateTime, GUID etc
  • Use an Out of Process mode if possible
    Session State provides for three configuration modes – In Process, Out of Process using stateview and Out of Process using SQL Server.
    In Process stores the session state data in memory with the same process as the application, this has the advantage of being the fastest mode but it also means that all session data is lost when the app restarts. The app restart is more common than many developers believe, in addition to server and IIS restarts any change in the web.config or global.asax file will restart the app and all session state data can be lost.
    Out of Process (stateserver) stores the session data in memory but in a different process, if you are running a web farm this can even be on a separate machine. Out of Process (SQLServer) stores the session data in SQL Server which is the most stable as it will be recoverable in all scenarios except a database failure but it is also the slowest. Both Out of Process modes protect the session data from loss due to an app restart.
  • Do not store sensitive data in Session State.
    SessionID’s which identify user sessions are sent in clear text and can be intercepted by nefarious users. Once a user’s SessionID has been obtained, data stored in the Session State associated with that SessionID can be easily accessed. Thus you should avoid using Session State to store sensitive data or use SSL or encryption of the data to protect it.
  • Allow users to log out of an application
    You should allow users to log out of the app, upon logon the app should call the Abandon method. This will reduce the scope for a malicious user to get hold of  the unique identifier in the URL and then use it for retrieving user data stored in session state.

ASP.NET Security Tutorial

Securing an ASP.NET application is paramount for any project. Here (in no particular order), in this tutorial we present the primary ASP.NET security best practices:

  • Ensure system patches are fully up-to-date
    Not really an ASP.NET specific best practice but since ASP.NET relies on the underling OS for its operation it is essential to ensure the OS to fully patched with the latest security updates.
  • Secure all connection strings
    Typically an app’s database will stored its most sensitive data so preventing unauthorized reading of the connection string is a must. The connection string should be stored in the web.config file and not in the code behind for pages and also not in the SqlDataSource control or other data source controls. For maximum security encrypt sensitive settings in config files – see Encrypt Connection Strings in ASP.NET for details.
  • Use parameterized queries or stored procedures instead of creating SQL commands by concatenating strings.
    It is possible to generate   the SQL for a command by building strings like below:

    SQLCmdStr = "Select * from users where username =' " & usernameTxt.Text  & "'

    This however allows for the possibility of SQL injection attacks by users directly typing SQL commands into text boxes which are then executed. Instead you can use a parameterized query as below:

    SQLCmdStr = “Select * from Users where Lastname =@LastName”
    SQLCmd.Parameters.Add(New SQLParameter(“@LastName”, ddl.SelectedItem.text))
  • Encrypt any sensitive data stored in View State
    View State is sometimes used to stored sensitive data sure as user names or even account numbers. Since View State is posted back to the server on every postback this data could be intercepted and read, therefore when any sensitive data is stored in View State the the page’s ViewStateEncryptionMode property should be set to true.
  • User input validation
    Always validate user input on the server even if it has been validated on the client since a user can easily bypass most client side validation by turning off javascript. The below code shows how to use Regex on the server-side to valid input:
  • using System.Text.RegularExpressions ;
    
    // Instance method:
    Regex regObj = new Regex(@"^[a-zA-Z'.\s]{1,40}$");
    Response.Write(regObj.IsMatch(Request.QueryString["InputName"]));
    
    // Static method:
    if (!Regex.IsMatch(Request.QueryString["InputName"],@"^[a-zA-Z'.\s]{1,40}$"))
    {
       // Name does not match expression
    }

    Note that user input does not only come from values input by the user on a form on the page. ASP.NET apps also take data form QueryStrings and cookies, these must also be validated in the same manner as input data.

    Continues…

ASP.NET ViewState Security

ASP.NET ViewState data is stored in a single Base64-encoded string  such as  this:

id="__VIEWSTATE" value="dDw3NDg2NdTI5MDg7Ozr4="/>

Since this value is not formatted in clear text, developers sometimes assume that their ViewState data is encrypted which is most certainly not the case. This data string can be reverse-engineered this and then viewed. This is an obvious security issue if sensitive data is being stored in ViewState.

To make ViewState secure, there are two choices, hash codes and ViewState encryption.

Use a hash code.

A hash code  is a cryptographically strong checksum. When you use a has code, ASP.NET calculates the checksum based on the current ViewState content data and then adds this to the hidden input field when the page  when is returned to the client.  On the page post back, ASP.NET then recalculates the checksum to  ensures a  match. If a malicious user were to  change the ViewState data, ASP.NET can detect the  the change reject the postback.
Hash codes are enabled by default,  however, sometimes developers elect  to disable hash codes to prevent problems on a web farm when  servers have different keys. Hash codes can be disabled on the page in the .aspx file’s Page directive:

<%@ Page EnableViewStateMac="false" ... %>

To disable hashing site-wide use the  ViewStateMac attribute of the pages  element in  web.config :

<configuration>
<system.web>
<pages enableViewStateMac="false" />
...
</system.web>
</configuration>

For more on hashing, please refer to C# Security – Hashing

Use ViewState Encryption.

Hash codes help to prevent ViewState data from being tampered with but they do not provide much assistance in preventing ViewState data from being read since hash codes can still be converted to clear text. To prevent ViewState being read, use the  ViewState Encryption, which can be turned on at the page level using the ViewStateEncryptionMode property of the Page directive:

<%@Page ViewStateEncryptionMode=”Always” … %>

Or site-wide in the web.config file:

<pages viewStateEncryptionMode=”Always” />

There are three settings for viewStateEncryptionMode:

  1. Always : All ViewState data is encrypted.
  2. Never : No ViewState data is encrypted.
  3. Auto : Data is only encrypted when specifically requested by the ASP.NET control.

The default setting is Auto so no data will be encrypted unless otherwise requested by a control on a page. For a control to request encryption in needs to call the Page.RegisterRequiresViewStateEncryption() method before it is rendered to HTML.

Note that using encryption incurs a performance penalty so it should only be used when necessary.

Using Custom Data Types in ASP.NET Profiles

ASP.NET Profile can also accept custom data types and they are relatively easy to implement

The first step is to create a class which wraps the information you require. In the class, you may use public member variables, but the preferred choice is full-fledged property procedures which will allow the  class to support data binding or other complex logic.

For example, the below code shows an  Address class which should be placed in the App_Code directory of the web app:

[Serializable()]
public class Address
{
private string fullName;
public string FullName {...}
private string streetNumber;
public string StreetNumber {...}
private string cityCode;
public string CityCode {...}
private string zip;
public string Zip  {...}
private string stateCode;
public string StateCode {...}
private string countryCode;
public string CountryCode {...}
public Address(string nameCode, string streetCode, string cityCode,
string zip, string stateCode, string countryCode)
{
NameCode = nameCode;
StreetCode = streeCodet;
CityCode = cityCode;
Zip= zip;
StateCode = stateCode;
CountryCode = countrCode;
}
public Address()
{ }
}

Next add a property in the web.config to declare it:

<properties>
<add name="CutomerAddress" type="Address" />
</properties>

Now you can use the Profile in your code.


To assign values to the Profile:

Profile.CutomerAddress.Zip = txtZip.Text;

To access the Profile data:

string zipStr;
zipStr = Profile.CutomerAddress.Zip;

Automatic Saves

The ASP.NET Profiles feature cannot detect changes in complex data types (ie anything other than strings, Boolean values, simple numeric types etc). So the Profile includes complex data types, ASP.NET will save the complete profile info at the end of every request which accesses the Profile. The behavior has an obvious performance cost. Therefore to optimize Profile performance when using  complex types, you can  set the profile property to be read-only (in the event it never changes).

Alternatively, you can disable the autosave behavior by using  the automaticSaveEnabled attribute in the <profile> element and setting this to  false. If you do this you will need to use Profile.Save() to explicitly save changes to the Profile. This approach is normally preferred as the parts of code which modify a Profile are easy to spot and you can easily add  Profile.Save() to the end of the code block:

Profile.CustomerAddress = new Address(txtName1.Text, txtStreet1.Text, txtCity1.Text,

txtZip1.Text, txtState1.Text, txtCountry1.Text);

Profile.Save();

Getting Started Using ASP.NET Profiles

ASP.NET Profiles are a very useful tool for  persisting user data. Most other methods of state management do not easily persist the data across user visits, but Profiles plug seamlessly into the ASP.NET Membership database to provide a convenient persistent store.

Defining Profile Properties

The first step to using Profiles is to defining them in the web.config file.  This is done by adding the <profile> section to the web.config file and the adding each property using a  <add> element nested inside the <properties> element:

<configuration>
<system.web>
...
<profile>
<properties>
<add name="Language"/>
<add name="NumberFormat"/>
<add name="JoinedDate"/>
</properties>
</profile>
</system.web>
...
</configuration>

In addition to name the <add> element accepts several attributes which should be used. By default the format of the Profile is set to String but can be set to any datatype, for example the above JoinedDate profile should have a attribute of type added with the associated data type:

<add name="JoinedDate" type="System.DateTime" />

defaultValue is another useful attribute which sets the default of the Profile. For example, this could be used the set the initial language a user’s preferences is set to:

<add name="Language" defaultValue="en" />

There are several additional attributes, namely:

  • serializeAs : The format to use for serializing this Profile (String, CML, Binary, or ProviderSpecific)
  • readOnly : This is a boolean which sets if the Profile can be updated.
  • allowAnonymous : A boolean which sets if the Profile can be used with anonymous profiles.
  • provider : The profile provider that is used to manage this property.

Access Profiles

Profile access is very simple. Just use Profile.ProfileName anywhere in an app to get the profile value for the user. For example:

String langStr = Profile.Language

Update Profiles

Updating ASP.NET  Profiles is also a simple procedure, just assign the value to the Profile and it will be stored:

Profile.Language  = langTxtBox.Text

Note that the Profile will not actually be written to the database (and therefore not stored) until the page life-cycle is complete. Therefore after updating a Profile, avoid accessing it unless the page has finished processing (as only the old value will be stored).

Be aware that Profiles do not come without issues. There is a performance cost to using Profiles inappropriately see ASP.NET Profile Performance for more details.

Run External Applications From ASP.NET

To run an external application from your ASP.NET web application use the System.Diagnostics.Process.Start method for calling the  application.

The first step for  running an external application from an ASP.NET app is to create a ProcessStartInfo object, and then pass  the name of the application to run as well as  command-line parameters it might require. In the sample code below, we use the Java runtime to execute a Java program named ExternalJavaProgram, in this case the name of the application to run is java and the only command-line parameter required is  the name of the Java program - ExternalJavaProgram.

In the page’s code-behind class :

  1. Import the System.Diagnostics namespace.
  2. Create a ProcessStartInfo object and then pass the name of the external app to run as well as all required command-line parameters.
  3. Set the working directory to the external app’s location.
  4. Start the external app process by calling the Start method of the Process class  and pass the ProcessStartInfo object.


Code Example

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

  {

  Process proc = null;
  ProcessStartInfo si = null;

  // create a new start info object with the program to execute
 // and the required command line parameters
  si = new ProcessStartInfo("java",  "ExternalJavaProgram");

  // set the working directory to the location of the the legacy program
  si.WorkingDirectory = Server.MapPath(".");

  // start a new process using the start info object
  proc = Process.Start(si);

  // wait for the process to complete before continuing
  proc.WaitForExit( );

  }  // Page_Load